Did you know that Rails has a built-in method to load configuration defined in
yml files? You don’t have to use any external gem to use it in your app.
If your application is named
guestbook we want to access file via
Guestbook.config. It should return a nested hash with your settings.
Let’s create config file first. In order to do this, create blank file in
config directory and name it
guestbook.yml. There are settings, such as payment information or logging credentials, that we don’t need to use during development or it’s dangerous to use them outside production. To solve this problem we will create sections. The default section and section for each environment: development, test, and production. You may be using also staging or other environment but we will focus on the common environments:
defaults: &defaults development: <<: *defaults production: <<: *defaults test: &test <<: *defaults
As you can see, each environment is using all settings from the default section. Because we fetch default settings at the top of each section we can easily overwrite each entry. Let’s say that we have
name setting but we want to display different name in production:
defaults: &defaults name: GuestBook development: <<: *defaults production: <<: *defaults name: GuestBook Production test: &test <<: *defaults
Now, the default name will be displayed everywhere except production. Having default section and a separate section for each environment gives us full control and flexibility. It's super useful when we are using external API where we have access to the production and development endpoints - if we want to switch the API environment we have to update only config not logic inside the code.
Config method creation
We have our config file created but now we want to access it using
Guestbook.config. In order to do this we have to update
config/application.rb file and define new class method:
module Guestbook def self.config Rails.application.config_for(:guestbook) end class Application ... end end
If you want to test how it works you can run
RAILS_ENV=development bundle exec rails c and then
RAILS_ENV=production bundle exec rails c and in this two cases calling
Guestbook.conifg[:name] gives different values.
Photo by Fancycrave from Pexels https://www.pexels.com/photo/architect-architectural-design-architecture-blueprint-595847/