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

Only use Spring if already loaded #511

Merged
merged 2 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions lib/dotenv/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,11 @@
Dotenv.instrumenter = ActiveSupport::Notifications

# Watch all loaded env files with Spring
begin
require "spring/commands"
ActiveSupport::Notifications.subscribe("load.dotenv") do |*args|
ActiveSupport::Notifications.subscribe("load.dotenv") do |*args|
if defined?(Spring)
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
Expand Down
13 changes: 12 additions & 1 deletion spec/dotenv/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
Rails.env = "test"
Rails.application = nil
Rails.logger = nil
Spring.watcher = Set.new # Responds to #add

begin
# Remove the singleton instance if it exists
Expand Down Expand Up @@ -76,6 +75,7 @@
end

it "watches other loaded files with Spring" do
stub_spring
application.initialize!
path = fixture_path("plain.env")
Dotenv.load(path)
Expand All @@ -93,6 +93,7 @@
subject { application.initialize! }

it "watches .env with Spring" do
stub_spring
subject
expect(Spring.watcher).to include(fixture_path(".env").to_s)
end
Expand Down Expand Up @@ -204,4 +205,14 @@
expect(Dotenv::Rails.logger).to be(logger)
end
end

def stub_spring
spring = Struct.new("Spring", :watcher) do
def watch(path)
watcher.add path
end
end

stub_const "Spring", spring.new(Set.new)
end
end