Vijay Chouhan
Vijay Chouhan

Reputation: 4883

How can I load multiple YAML files in rails application.rb

I have many yaml files in config/ And I want to load all yaml files.

EX: I have two .yml files name is: application.yml and linkedin.yml. I want to load both files with application.rb.

To achieve this goal I Have written code in application.rb:

ENV.update YAML.load_file('config/application.yml')[Rails.env] rescue {}
ENV.update YAML.load_file('config/linkedin.yml')[Rails.env] rescue {}

But this is not appropriate way, Please suggest me how can I load all yaml files access with ENV variable that.

Upvotes: 3

Views: 2374

Answers (1)

derekyau
derekyau

Reputation: 2946

Assuming that your YAML files are placed in the config folder, in your application.rb you can do this right under the requires (before the module definition)

APP_YAML = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'application.yml'))
LINKED_IN = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'linked_in.yml'))

This way, you can then access the contents of the file in a constant that is available everywhere in the app ie. LINKED_IN["secret"]

This is a great way to handle constants that you don't want to check in to source control, but actually I've found that using Figaro is the best way to handle constants. Essentially, Figaro will autogenerate/load an application.yml and all you have to do is put your constants in there.

After this, you can access with ENV["LINKED_IN_SECRET"] - as a plus, this emulates how Heroku would do it with their config:set variable system so you don't have to worry about environment changes :)

Upvotes: 2

Related Questions