Rails 5.2 から導入された credentials.yml.enc を利用して、
外部 API 実行の際の access_token 等を YAML から読み出して
利用する方法
YAML.load する際に、 一回 ERB を通すと credentials の中身の置き換えてくれる
hogehoge.rb
yaml = Rails.root.join('config/hogehoge.yml')
Rails.application.config.hogehoge_config =
if yaml.exist?
YAML.load(ERB.new(yaml.read).result)[Rails.env].to_options
else
{}
end
hogehoge.yml
default: &default
endpoint: https://api.hogehoge.com/
access_token: <%= Rails.application.credentials.dig(:hogehoge, :access_token) %>
development:
<<: *default
production:
<<: *default
test:
<<: *default
credentials.yml.enc
hogehoge:
access_token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX