108
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2013-11-28

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

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

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

参考

108
98
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
108
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?