Class: Dotenv::Rails

Inherits:
Rails::Railtie
  • Object
show all
Defined in:
lib/dotenv/rails.rb

Overview

Rails integration for using Dotenv to load ENV variables from a file

Constant Summary collapse

TEST_RAKE_TASKS =
/^(default$|test(:|$)|parallel:spec|spec(:|$))/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRails

Returns a new instance of Rails.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dotenv/rails.rb', line 23

def initialize
  super()
  config.dotenv = ActiveSupport::OrderedOptions.new.update(
    # Rails.logger is not available yet, so we'll save log messages and replay them when it is
    logger: Dotenv::ReplayLogger.new,
    overwrite: false,
    files: [
      root.join(".env.#{env}.local"),
      (root.join(".env.local") unless env.test?),
      root.join(".env.#{env}"),
      root.join(".env")
    ].compact,
    autorestore: env.test?
  )
end

Class Method Details

.loadObject

Rails uses ‘#method_missing` to delegate all class methods to the instance, which means `Kernel#load` gets called here. We don’t want that.



81
82
83
# File 'lib/dotenv/rails.rb', line 81

def self.load
  instance.load
end

Instance Method Details

#deprecatorObject

:nodoc:



75
76
77
# File 'lib/dotenv/rails.rb', line 75

def deprecator # :nodoc:
  @deprecator ||= ActiveSupport::Deprecation.new
end

#envObject

The current environment that the app is running in.

When running ‘rake`, the Rails application is initialized in development, so we have to check which rake tasks are being run to determine the environment.

See github.com/bkeepers/dotenv/issues/219



65
66
67
68
69
70
71
72
# File 'lib/dotenv/rails.rb', line 65

def env
  @env ||= if defined?(Rake.application) && Rake.application.top_level_tasks.grep(TEST_RAKE_TASKS).any?
    env = Rake.application.options.show_tasks ? "development" : "test"
    ActiveSupport::EnvironmentInquirer.new(env)
  else
    ::Rails.env
  end
end

#loadObject

Public: Load dotenv

This will get called during the ‘before_configuration` callback, but you can manually call `Dotenv::Rails.load` if you needed it sooner.



43
44
45
# File 'lib/dotenv/rails.rb', line 43

def load
  Dotenv.load(*files, overwrite: overwrite)
end

#overloadObject



47
48
49
50
# File 'lib/dotenv/rails.rb', line 47

def overload
  deprecator.warn("Dotenv::Rails.overload is deprecated. Set `Dotenv::Rails.overwrite = true` and call Dotenv::Rails.load instead.")
  Dotenv.load(*files, overwrite: true)
end

#rootObject

Internal: ‘Rails.root` is nil in Rails 4.1 before the application is initialized, so this falls back to the `RAILS_ROOT` environment variable, or the current working directory.



55
56
57
# File 'lib/dotenv/rails.rb', line 55

def root
  ::Rails.root || Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd)
end