-
Notifications
You must be signed in to change notification settings - Fork 500
/
rails.rb
88 lines (73 loc) · 2.79 KB
/
rails.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require "dotenv"
Dotenv.instrumenter = ActiveSupport::Notifications
# Watch all loaded env files with Spring
begin
require "spring/commands"
ActiveSupport::Notifications.subscribe(/^dotenv/) do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
Spring.watch event.payload[:env].filename if Rails.application
end
rescue LoadError, ArgumentError
# Spring is not available
end
module Dotenv
# Rails integration for using Dotenv to load ENV variables from a file
class Rails < ::Rails::Railtie
attr_accessor :overwrite, :files
def initialize
@overwrite = false
@files = [
root.join(".env.#{env}.local"),
(root.join(".env.local") unless env.test?),
root.join(".env.#{env}"),
root.join(".env")
].compact
end
# 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.
def load
Dotenv.load(*files, overwrite: overwrite)
end
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
# 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.
def root
::Rails.root || Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd)
end
def env
env = ::Rails.env
# Dotenv loads environment variables when the Rails application is initialized.
# When running `rake`, the Rails application is initialized in development.
# Rails includes some hacks to set `RAILS_ENV=test` when running `rake test`,
# but rspec does not include the same hacks.
#
# See https://github.com/bkeepers/dotenv/issues/219
if defined?(Rake.application)
task_regular_expression = /^(default$|parallel:spec|spec(:|$))/
if Rake.application.top_level_tasks.grep(task_regular_expression).any?
env = ActiveSupport::EnvironmentInquirer.new(Rake.application.options.show_tasks ? "development" : "test")
end
end
env
end
def deprecator # :nodoc:
@deprecator ||= ActiveSupport::Deprecation.new
end
# Rails uses `#method_missing` to delegate all class methods to the
# instance, which means `Kernel#load` gets called here. We don't want that.
def self.load
instance.load
end
initializer "dotenv.deprecator" do |app|
app.deprecators[:dotenv] = deprecator
end
config.before_configuration { load }
end
Railtie = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Dotenv::Railtie", "Dotenv::Rails", Dotenv::Rails.deprecator)
end