LoginSignup
0
1

More than 3 years have passed since last update.

Rails5 で credentials を利用して、 外部 API の設定を yml に保存して読み出す

Posted at

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
0
1
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
0
1