Few days ago I stummbled upon a cool helper method in Rails called config_for. It's super useful to read any YAML based config files with ease. Let me show you.

First the basic, let's read the config/database.yml:

Rails.application.config_for(:database)
# => {:adapter=>"postgresql", :encoding=>"unicode", :pool=>5, :database=>"App_dev"}

This will spit out current env specific config. You can read all the YAML files under config directory with this syntax, including the nested ones. Just pass in the sub path like this:

Rails.application.config_for('databases/ci')

Need to read the values of a different env? This method also supports a second param:

Rails.application.config_for(:database, env: :production)
# => {:adapter=>"postgresql", :encoding=>"unicode", :user=>"mbabar", :pool=>5, :database=>"App_prod", :username=>"deployer", :password=>nil}

Okay, hold your horses, I need to read files that are not in config directory, maybe in the root of the app or somewhere else. Drumroll please...

Rails.application.config_for(Rails.root.join('kabel.yml'))
# => {:adapter=>"async"}

You can just path in a Pathname object instead of filename as first param, it'll read your file correctly.

Do you use any other little known but useful methods of Rails? Let us know in the comments down below please.

Happy hacking!




What's on your mind?


2 Comments