LoginSignup
11
7

More than 5 years have passed since last update.

Rails.application の config_for を使って、ユーザ定義の設定値を定義する

Posted at

Rails のアプリケーション開発の折、

  • プロダクトに固有の設定を定義したい
  • 設定値なので YAML で管理したいが、読み込みは実装したくない
  • でも config/secrets.yml に置くのは違う感じがする
    • パスワードやAPIキーの定義じゃあるまいし、別に隠してるわけでは…

というようなことがあった場合、Rails 4.2 から使えるようになった config_for で、良い感じに分割しつつ定義ができるとか、できないとか。

config/preference.yml
default: &default
  app_name: "I'm stillalive"
  cheat_enabled: true

# 環境ごとの差がない場合はやや勿体無いような気もしますが、気にせず
development:
  <<: *default
test:
  <<: *default
production:
  <<: *default
config/application.rb
# config.x 名前空間はユーザ定義用に用意されているらしいので、折角なので利用(必須ではない)
config.x.preference = config_for(:preference)

定義方法からお察しの通り、環境ごとの設定値を個別に定義でき、その点でも便利なのですが、実行結果は単なる Hash オブジェクトとなるため、参照時にはやや使いにくい印象を受けるような……?

Rails.configuration.x.preference["cheat_enabled"] #=> true
Rails.configuration.x.preference[:cheat_enabled] #=> nil
Rails.configuration.x.preference.cheat_enabled #=> NoMethodError

というわけで、ActiveSupport::OrderedOptions を用いる場合の例。

config/application.rb
config.x.preference = ActiveSupport::InheritableOptions.new config_for(:preference).symbolize_keys

こうすれば、以下の実行ができるように。

if Rails.configuration.x.preference.cheat_enabled
  puts "升乙"
end
11
7
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
11
7