4
5

More than 1 year has passed since last update.

railsのconfig_forで環境ごとに設定を切り替える

Last updated at Posted at 2022-02-07

環境

rails6

はじめに

開発環境(development)と本番環境(production)で異なる設定値を持たせたい場合があります。むしろその方が一般的だと思います。
それぞれの環境で出力させるパスが違うとか、Titleを変えるとかの場合、いちいちif文を書きたくないですよね。

ただの設定値として設定させたい場合

config/application.rb
module MyApp
  class Application < Rails::Application
     config.hello = "hello"
  end
end

以下のように呼び出せます。

Rails.configuration.hello
=> "hello"

環境ごとに設定を分けたい

config_forを有効に

config/application.rb
module MyApp
  class Application < Rails::Application
     #以下を追記するとconfig_forが有効になる
     #config_forの引数をシンボルで渡すことでconfig以下のymlファイル全体を読み込む
     #以下の場合、config以下にあるconf.ymlを読み込む
     config.app = config_for(:conf)
  end
end

confファイル

ymlの書式で環境ごとの設定を書きます。この辺はdatabase.ymlと一緒。
shared設定がサポートされており、共通の設定はここに書きます。

config/conf.yml
#デフォルト値はここに
default: &default
  app_name: "MyApp"

#各ステージ共通の設定はここに
shared:
  cheat_enabled: false

#開発環境
development:
  <<: *default
  app_name: "MyApp開発"

#テスト環境
test:
  <<: *default
  app_name: "MyAppテスト"

#本番環境
production:
  <<: *default
  cheat_enabled: True

確認

本番環境のapp_nameはデフォルト値、cheat_enabledは上書きされているのがわかります。

###開発環境
$ rails c
> Rails.configuration.app
=> {:cheat_enabled=>false, :app_name=>"MyApp開発"}

###テスト環境
$ rails c -e test
> Rails.configuration.app
=> {:cheat_enabled=>false, :app_name=>"MyAppテスト"}

###本番環境
$ rails c -e production
> Rails.configuration.app
=> {:cheat_enabled=>true, :app_name=>"MyApp"}

#rails上での使い方
Rails.configuration.appでハッシュを指定して使用できます。

<%= Rails.configuration.app[:app_name] %>

参考

4
5
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
4
5