Skip to content

Commit c2803fb

Browse files
committed
Add rails_available? check to prevent nil Rails.application
The previous implementation didn't check if Rails.application was available before calling load_tasks, which caused test failures. This adds the rails_available? method to check if Rails is properly initialized. Also updates run_rake_task_directly to use task.reenable for better re-execution support. Fixes RSpec test failures in pack_generator_spec.rb
1 parent 387239f commit c2803fb

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

lib/react_on_rails/dev/pack_generator.rb

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,27 @@ def generate(verbose: false)
2525
private
2626

2727
def run_pack_generation(silent: false)
28-
# If we're already inside a Bundler context (e.g., called from bin/dev),
28+
# If we're already inside a Bundler context AND Rails is available (e.g., called from bin/dev),
2929
# we can directly require and run the task. Otherwise, use bundle exec.
30-
if defined?(Bundler)
30+
if defined?(Bundler) && rails_available?
3131
run_rake_task_directly(silent: silent)
3232
else
3333
run_via_bundle_exec(silent: silent)
3434
end
3535
end
3636

37+
def rails_available?
38+
return false unless defined?(Rails)
39+
return false unless Rails.respond_to?(:application)
40+
return false if Rails.application.nil?
41+
42+
true
43+
end
44+
3745
def run_rake_task_directly(silent: false)
3846
require "rake"
3947

40-
# Load Rails environment if not already loaded
41-
require File.expand_path("config/environment", Dir.pwd) unless defined?(Rails)
42-
43-
Rake::Task.clear
48+
# Load tasks only if not already loaded (don't clear all tasks)
4449
Rails.application.load_tasks unless Rake::Task.task_defined?("react_on_rails:generate_packs")
4550

4651
if silent
@@ -51,7 +56,9 @@ def run_rake_task_directly(silent: false)
5156
end
5257

5358
begin
54-
Rake::Task["react_on_rails:generate_packs"].invoke
59+
task = Rake::Task["react_on_rails:generate_packs"]
60+
task.reenable # Allow re-execution if called multiple times
61+
task.invoke
5562
true
5663
rescue StandardError => e
5764
warn "Error generating packs: #{e.message}" unless silent

0 commit comments

Comments
 (0)