Farooq
Farooq

Reputation: 1995

How to store and call data from YAML file using Ruby?

I'm writing features and step definitions using Cucumber and Capybara, I want to store user credentials in a YAML file.

My question is if I have a cred.yml file in my support/config.yml, and I load the file in my env.rb (CONFIG = YAML.load_file("/config/config.yml")), will all of the information be accessible? If so how will I access/call user1 from env_1 for example?

Or if I want to only load one/multiple select environment at a time, how would I do that? And how would I access/call the different users?

Something like this: CONFIG = YAML.load_file("/config/config.yml")[ENV]?

config.yml file contents:

env_1:

 `user1: admin`
 `password1: password`
 `user2: teacher`
 `password2: password`

env_2:

 `user: student`
 `password: password`
 `user2: assistant`
 `password2: password`

Upvotes: 1

Views: 5737

Answers (1)

Stefan
Stefan

Reputation: 114208

YAML::load_file returns a nested hash:

require 'yaml'
config = YAML.load_file("config.yml") #=> {"env_1"=>{"user1"=>"admin", "password1"=>"password", "user2"=>"teacher", "password2"=>"password"}, "env_2"=>{"user"=>"student", "password"=>"password", "user2"=>"assistant", "password2"=>"password"}}

You can access env_1 with:

config["env_1"] #=> {"user1"=>"admin", "password1"=>"password", "user2"=>"teacher", "password2"=>"password"}

And its values with:

config["env_1"]["user1"] #=> "admin"
config["env_1"]["user2"] #=> "teacher"

Accessing env_2 works accordingly:

config["env_2"]["user"]  #=> "student"

Assuming your config.yml looks like this:

env_1:
  user1: admin
  password1: password
  user2: teacher
  password2: password
env_2:
  user: student
  password: password
  user2: assistant
  password2: password

Upvotes: 4

Related Questions