LoginSignup
5
6

More than 3 years have passed since last update.

Rails の環境変数の設定方法

Posted at

Rails 用の環境変数の設定方法について備忘録を含めまとめたいと思います。

今回は環境変数を簡単に扱える Gem である dotenv-rails を使用いたします。

Gemfileにdotenv-railsを追加する。

gemfile
gem 'dotenv-rails'
ターミナル
$ bundle install

dotenv-rails を導入すると、.env ファイル内に設定された環境変数を Rails 起動時に、自動読み込みします。

環境変数を設定するために、.env ファイルを新規作成、Gemfile と同じ階層に設置してください。
その後.envファイルに環境変数を記述してください。

.env
HEROKU_ID=hoge
HEROKU_PASS=hoge
hoge.rb
ID = ENV['HEROKU_ID']
PASS = ENV['HEROKU_PASS']

また.envに定義されている情報を不正利用されないように、Git の管理から外す必要があります。
そのため、.gitignoreに下記のように記載してください。

# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile '~/.gitignore_global'

# Ignore bundler config.
/.bundle

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# Ignore Byebug command history file.

.env

既にgitにpushしてしまっている場合下記のコマンドで.envをgitの管理から外してください。

git rm --cached .env

以上となります。
ご参考になれば幸いです。

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