Nahuel
Nahuel

Reputation: 11

How to create a config file for multiple environments in Ruby?

I don't want to confuse you so what I want to do is the following:

I have three environments:

www.env1.com
www.env2.com
www.env3.com

I want to create something to define the setup phase according the environment over which I want to run the scripts, that is:

Current set-up:

def setup
  @verification_errors = []
  @selenium = Selenium::Client::Driver.new(
    :host => "localhost",
    :port => 4444,
    :browser => "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
    :url => "www.env1.com",
    :timeout_in_second => 60
  )

  @selenium.start_new_browser_session
end

What I want:

def setup
  @verification_errors = []
  @selenium = Selenium::Client::Driver.new( 
    :host => "localhost",
    :port => 4444,
    :browser => "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
    **:url => This parameter configurable from a file or other source.**
    :timeout_in_second => 60
  )

  @selenium.start_new_browser_session
end

If this is possible I can switch environments without having to re-write all test cases.

Hope you can help me out, I really need to do this.

Upvotes: 1

Views: 1943

Answers (1)

the Tin Man
the Tin Man

Reputation: 160551

YAML is a great data serialization language for handling configuration information. It comes with Ruby so you only have to do:

require 'yaml'

to load it in, then something like:

configuration = YAML::load_file('path/to/yamldata.yaml')

All your configuration data will be available inside the configuration variable.

Generally I create a stub for my YAML files by writing some Ruby code, defining the configuration hash that contains it, then telling YAML to generate the file for me. See the docs for load_file and dump for ways to do that.

For something like you're doing I'd create a hash like:

configuration = {
  'env1' => "www.env1.com",
  'env2' => "www.env2.com",
  'env3' => "www.env3.com",
}

Using YAML::dump(configuration) returns:

--- 
env1: www.env1.com
env2: www.env2.com
env3: www.env3.com

which you'd want to write to your .yaml file, then load later at run-time and access it like:

@selenium = Selenium::Client::Driver.new( 
  :host => "localhost",
  :port => 4444,
  :browser => "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
  :timeout_in_second => 60
  :url => configuration['env1'],
)

You can replace 'env1' with the other keys to use env2 or env3.

Rails uses YAML to make one file handle the development, test and production information for an application. At work I use it to do similar things, where one file contains our development and production environmental information for apps, plus the definitions of some hashes we need to maintain, but don't want to have to modify the code to do so.

Upvotes: 4

Related Questions