From 725ee063e17bd66f7f1272e202c99f1f504aa538 Mon Sep 17 00:00:00 2001 From: Jacob Carlborg Date: Fri, 20 Dec 2024 09:37:22 +0100 Subject: [PATCH] Fix #27: Make sure only one listener is running By default, only enable hotwire-spark when starting the Rails server. This prevents starting multiple listeners which can occur if one starts the Rails console or runs a script (`rails runner`). --- lib/hotwire/spark/engine.rb | 2 +- test/enabled_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 test/enabled_test.rb diff --git a/lib/hotwire/spark/engine.rb b/lib/hotwire/spark/engine.rb index 677c3a9e..405b8bf9 100644 --- a/lib/hotwire/spark/engine.rb +++ b/lib/hotwire/spark/engine.rb @@ -7,7 +7,7 @@ class Engine < ::Rails::Engine config.hotwire = ActiveSupport::OrderedOptions.new unless config.respond_to?(:hotwire) config.hotwire.spark = ActiveSupport::OrderedOptions.new config.hotwire.spark.merge! \ - enabled: Rails.env.development?, + enabled: Rails.env.development? && !defined?(Rails::Server).nil?, css_paths: File.directory?("app/assets/builds") ? %w[ app/assets/builds ] : %w[ app/assets/stylesheets ], html_paths: %w[ app/controllers app/helpers app/models app/views ], stimulus_paths: %w[ app/javascript/controllers ] diff --git a/test/enabled_test.rb b/test/enabled_test.rb new file mode 100644 index 00000000..25e74d3a --- /dev/null +++ b/test/enabled_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class EnabledTest < ActiveSupport::TestCase + test "that Hotwire-Spark is only enabled when starting the Rails server" do + script = <<~RUBY.strip + Hotwire::Spark.enabled? ? exit(1) : exit(0) + RUBY + + assert system({ "RAILS_ENV" => "development" }, "rails", "runner", script, chdir: Rails.application.root) + end +end