マイペースなRailsおじさん

Ruby、Ruby on Rails、オブジェクト指向設計を主なテーマとして扱います。だんだん大きくなっていくRuby on Rails製プロダクトのメンテナンス性を損なわない方法を考えたり考えなかったりしている人のブログです。

Use rails application configuration to read credentials instead of reading it directly.

When we use secret values, we can utilize credentials. Explained at below page.
Securing Rails Applications — Ruby on Rails Guides

For example, to use secret information for omniauth configuration, we can read from credentials.

  config.omniauth(
    :twitter,
    Rails.application.credentials.twitter[:api_key],
    Rails.application.credentials.twitter[:api_secret]
  )

But I don't prefer user credentials directly. Because it is just a configuration. In staging or testing environment, it may not be secret.

I think mediate Rails.configuration to read values.

config/twitter.yml

shared:
  api_key: <%= Rails.application.credentials.twitter[:api_key] %>
  api_secret: <%= Rails.application.credentials.twitter[:api_secret] %>
test:
  api_key: dummy
  api_secret: dummy

config/application.rb

config.twitter = config_for(:twitter)

initializers/devise.rb

  config.omniauth(
    :twitter,
    Rails.configuration.twitter[:api_key],
    Rails.configuration.twitter[:api_secret]
  )

In this case, there are 2 benefits.

  1. Encrypt only truly secret values.
  2. Works correctly in environments do not have master.key.

So, I prefer use credentials only in yaml configuration file or enviroment/*.rb file.