Help us understand the problem. What is going on with this article?

Railsで定数を一元管理する(settingslogic)

More than 5 years have passed since last update.

2014/11/19追記
最近はrails_configに乗り換えました。
環境毎にファイルが分かれるので定数の数が増えてきた場合はrails_configの方が管理しやすいです。

Railsで定数を一元管理する(rails_config)


Ruby2.0, Rails4で確認

railsで定数を一元管理したい時にsettingslogic gemをよく使っています。

  • gem追加
gem 'settingslogic'
  • bundle install
./bin/bundle install
  • initializer設定

ファイル名に0_をつけることで一番最初にsettingslogicのinitializerが読み込まれるようになり、他のinitialier内で設定ファイルを呼び出そうとした際にエラーが起きないようにしています。

config/initializers/0_settings.rb
class Settings < Settingslogic
  source "#{Rails.root}/config/settings.yml"
  namespace Rails.env
end
  • settings.ymlに定数を記述
config/settings.yml
defaults: &defaults
  cool:
    saweet: nested settings
  neat_setting: 24
  awesome_setting: <%= "Did you know 5 + 5 = #{5 + 5}?" %>

development:
  <<: *defaults
  neat_setting: 800

test:
  <<: *defaults

production:
  <<: *defaults
  • consoleから試してみる
./bin/rails c

Loading development environment (Rails 4.0.0)
[1] pry(main)> Settings.cool
=> {"saweet"=>"nested settings"}
[2] pry(main)> Settings.cool.saweet
=> "nested settings"
[3] pry(main)> Settings.awesome_setting
=> "Did you know 5 + 5 = 10?"
[4] pry(main)> Settings.neat_setting
=> 800

定数を一元管理できるのでスッキリしますね。

詳細に関しては公式ドキュメントを参照ください。

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした