[Ruby] [Rails] Let’s manage constants with config gem

less than 1 minute read

environment

$ rails -v
Rails 6.0.3.1
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]

First, install Gem

Gemfile


gem 'config'
$ bundle install --path vendor/bundle

Initialize config

Install related files for config initialization

$ bundle exec rails g config:install

Constant definition and usage

config/settings.yml


service: 
  name: 'vdeep' 
  url: 'http://vdeep.net'

authentication_password: "foobarbaz"
$ rails c

> Settings.service.name
=> "vdeep"

> Settings.service[:name]
=> "vdeep"

> Settings[:service][:name]
=> "vdeep"

> Settings.authentication_password
=> "foobarbaz"