From 54aa1f65dec1ea45354bb3f4c72c9bce200b7c20 Mon Sep 17 00:00:00 2001 From: Rune Philosof <57357936+runephilosof-abtion@users.noreply.github.com> Date: Tue, 17 Sep 2024 13:02:25 +0200 Subject: [PATCH 1/2] Only use Spring if already loaded This makes it possible for the user to selectively use Spring on a command to command basis Fixes https://github.com/bkeepers/dotenv/issues/510 --- lib/dotenv/rails.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/dotenv/rails.rb b/lib/dotenv/rails.rb index 2453eea..a56bd84 100644 --- a/lib/dotenv/rails.rb +++ b/lib/dotenv/rails.rb @@ -10,14 +10,11 @@ Dotenv.instrumenter = ActiveSupport::Notifications # Watch all loaded env files with Spring -begin - require "spring/commands" +if defined?(Spring) ActiveSupport::Notifications.subscribe("load.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 From 8c7e46088c1ee53ce7854252e78ce13565dc42f0 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Tue, 17 Sep 2024 11:10:29 -0400 Subject: [PATCH 2/2] Fix tests for spring changes --- lib/dotenv/rails.rb | 4 ++-- spec/dotenv/rails_spec.rb | 13 ++++++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/dotenv/rails.rb b/lib/dotenv/rails.rb index a56bd84..ab4613a 100644 --- a/lib/dotenv/rails.rb +++ b/lib/dotenv/rails.rb @@ -10,8 +10,8 @@ Dotenv.instrumenter = ActiveSupport::Notifications # Watch all loaded env files with Spring -if defined?(Spring) - 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 diff --git a/spec/dotenv/rails_spec.rb b/spec/dotenv/rails_spec.rb index f50088a..1e4bd0a 100644 --- a/spec/dotenv/rails_spec.rb +++ b/spec/dotenv/rails_spec.rb @@ -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 @@ -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) @@ -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 @@ -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