I am trying to retrieve key value pairs defined on two different .yml files. Is it possible to do so in a single Ruby file ?
Asked
Active
Viewed 821 times
0
-
3Sure. Why not? Can you provide code so we can know your issue? – Abdo Feb 20 '14 at 08:42
1 Answers
1
Sure. Try this:
require 'yaml'
file1 = YAML.load_file("/home/abdo/settings.yml")
file2 = YAML.load_file("/home/abdo/database.yml")
This is an example I'm using in Rails to load a settings file:
SETTINGS = YAML.load_file("#{Dir.pwd}/config/settings.yml")[Rails.env]
If you want to load multiple files in 1 hash, you can do the following:
files = %w(database.yml settings.yml)
yamls = files.map { |f| YAML.load_file("#{Dir.pwd}/config/#{f}") }
H = files.each_with_object({}).with_index { |(e, hash), i| hash[e] = yamls[i] }
You can access H["database.yml"]
to get the Hash
representing the file with name database.yml
If you want to load a list of files following a certain pattern in a directory, you can use Dir.glob
as mentioned in Iterate through every file in one directory
EDIT If your YAML files have non-conflicting data (data that does not get overridden when merged) and you'd like to merge all of them in a single Hash
, you can do:
yamls.inject({}) { |hash, yaml| hash.merge(yaml) }
-
Thank you Abdo, The problem we are facing in our project is that there are 25-30 .yml configuration files. Is there any way for us to merge all the data present in these files in some way so that it can referenced by a single referencing variable ? We do not want to use a single .yml file for maintainability. – user3231104 Feb 20 '14 at 09:52
-