1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

APIキーはsecrets.ymlから読み込む

Last updated at Posted at 2019-08-15

備忘録メモ

RailsでAPIキーのような見られたくない情報をプログラム内にベタ書きしたくない時は、config/secrets.ymlに記述することで呼び出せるようになる

Twitter APIを使うとして...

ymlファイルを作る

設定したいキー情報をsecrets.ymlに記述する

config/secrets.yml
default: &default
  twitter_consumer_key: "Consumer API key"
  twitter_consumer_secret: "Consumer API secret key"
  twitter_access_token: "Access token"
  twitter_access_token_secret: "Access token secret"

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

Controller側で呼び出す

secrets.ymlの情報はRails.application.secretsで呼び出せる

twitter_controller.rb
class TwitterController < ApplicationController
  def new
    # ymlに記述したキー情報を取得する
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key        = Rails.application.secrets.twitter_consumer_key
      config.consumer_secret     = Rails.application.secrets.twitter_consumer_secret
      config.access_token        = Rails.application.secrets.twitter_access_token
      config.access_token_secret = Rails.application.secrets.twitter_access_token_secret
    end
    # tweetする
    @client.update("This is test")
  end
end
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?