Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Rails apps to use Dotenv.overload. #149

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -59,6 +59,13 @@ require 'dotenv'
Dotenv.load
```

If you need to overload environment variables:

```ruby
require 'dotenv'
Dotenv.overload
```

Alternatively, you can use the `dotenv` executable to launch your application:

```shell
Expand Down
22 changes: 19 additions & 3 deletions lib/dotenv/rails.rb
Expand Up @@ -15,12 +15,20 @@ class Railtie < Rails::Railtie
# This will get called during the `before_configuration` callback, but you
# can manually call `Dotenv::Railtie.load` if you needed it sooner.
def load
Dotenv.instrumenter = ActiveSupport::Notifications
configure_spring if defined?(Spring)

configure_load_options
Dotenv.load Rails.root.join('.env')
end

# Public: Overload dotenv
#
# Manually called if you need to overload the values of existing
# environment variables. Useful if you are reloading environment as
# part of a zero-downtime deployment.
def overload
configure_load_options
Dotenv.overload Rails.root.join('.env')
end

# Internal: Watch all loaded env files with spring
def configure_spring
ActiveSupport::Notifications.subscribe(/^dotenv/) do |*args|
Expand All @@ -34,5 +42,13 @@ def configure_spring
def self.load
instance.load
end

private

# Internal: set up the instrumenter and configure Spring if Spring is loaded.
def configure_load_options
Dotenv.instrumenter = ActiveSupport::Notifications
configure_spring if defined?(Spring)
end
end
end
20 changes: 19 additions & 1 deletion spec/dotenv/rails_spec.rb
Expand Up @@ -36,7 +36,7 @@ def add(*items)
end
end

context 'load' do
context 'load methods' do
before { Dotenv::Railtie.load }

it 'watches .env with Spring' do
Expand All @@ -52,5 +52,23 @@ def add(*items)
it 'loads .env' do
expect(ENV).to have_key('DOTENV')
end

context 'load' do
before { ENV['DOTENV'] = 'false' }

it 'does not overload .env' do
Dotenv::Railtie.load
expect(ENV['DOTENV']).to eq 'false'
end
end

context 'overload' do
before { ENV['DOTENV'] = 'false' }

it 'overloads .env' do
Dotenv::Railtie.overload
expect(ENV['DOTENV']).to eq 'true'
end
end
end
end