LoginSignup
127

More than 5 years have passed since last update.

Dotenv使ってみた

Last updated at Posted at 2014-03-20

Dotenvとは

  • .envファイルに書いた設定を環境変数として簡単に読み込めるgem
  • .env自体はruby以外からも使えて便利
    • sourceやshで環境変数設定とか
  • 複数のツールで同じような設定使いたい時とか便利

さっそく使ってみる

  • 準備
$ echo -e "source 'https://rubygems.org'\ngem 'dotenv'"
$ bundle install
$ echo HOGE=\"hogehoge\" > .env
dotenv1.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.load
puts ENV["HOGE"]
  • 実行結果
$ ruby dotenv1.rb

hogehoge

既に環境変数が設定されている場合、Dotenv.loadでは上書きされない

$ export HOGE="hoooogeeee"
$ ruby dotenv1.rb 
hoooogeeee
hoooogeeee

ファイル指定でもloadできる

dotenv2.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.load ".env.test"
puts ENV["HOGE"]
$ echo HOGE=\"hogehoge\" > .env.test
$ ruby dotenv2.rb

fugafuga

.envファイルがない場合は何もloadしない

dotenv3.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.load ".env.aaa"
puts ENV["HOGE"]
$ ruby dotenv3.rb


$ ls .env.aaa
ls: cannot access .env.aaa: そのようなファイルやディレクトリはありません

スクリプト内で環境変数を上書きしたい

dotenv4.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.overload
puts ENV["HOGE"]
$ export HOGE="hoooogeeee"
$ ruby dotenv4.rb 
hoooogeeee
hogehoge

.envファイルがない場合、例外を発生させたい

dotenv5.rb
require 'dotenv'

Dotenv.load! ".env.aaa"
$ ls .env.aaa
$ ruby dotenv5.rb 
/home/***/.rvm/gems/***/gems/dotenv-0.10.0/lib/dotenv.rb:24:in `block in load!': No such file or directory - /home/***/tmp/.env.aaa (Errno::ENOENT)
    from /home/***/.rvm/gems/***/gems/dotenv-0.10.0/lib/dotenv.rb:22:in `each'
    from /home/***/.rvm/gems/***/gems/dotenv-0.10.0/lib/dotenv.rb:22:in `load!'
    from dotenv5.rb:4:in `<main>'

複数ファイルをloadしたい

dotenv6.rb
require 'dotenv'

puts ENV["HOGE"]
puts ENV["FUGA"]
Dotenv.load(
  File.join(File.dirname(File.expand_path(__FILE__)), '.env'),
  File.join(File.dirname(File.expand_path(__FILE__)), '.env.second')
)
puts ENV["HOGE"]
puts ENV["FUGA"]
$ echo FUGA=\"fugafuga\" > .env.second
$ ruby dotenv6.rb 


hogehoge
fugafuga

複数ファイルをloadして環境変数が重複した場合、最初に読み込んだ値が適用される

dotenv7.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.load(
  File.join(File.dirname(File.expand_path(__FILE__)),
 '.env'),
  File.join(File.dirname(File.expand_path(__FILE__)), '.env.third')
)
puts ENV["HOGE"]
$ echo HOGE=\"hhhhhhhogeeeeee\" > .env.third
$ ruby dotenv7.rb 

hogehoge
  • 別の書き方でも確認
dotenv8.rb
require 'dotenv'

puts ENV["HOGE"]
Dotenv.load File.join(File.dirname(File.expand_path(__FILE__)), '.env')
puts ENV["HOGE"]
Dotenv.load File.join(File.dirname(File.expand_path(__FILE__)), '.env.third')
puts ENV["HOGE"]
$ ruby dotenv8.rb 

hogehoge
hogehoge

railsやcapistrano向けのは機会があれば書く。

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
127