Skip to content

Commit 455b8e4

Browse files
Load Rake tasks only once for command suggestions
Follow-up to rails#47208. `UnrecognizedCommandError` calls `printing_commands` to make "Did you mean?" suggestions. `printing_commands` calls `RakeCommand::rake_tasks`, which loads the Rake tasks if they have not been memoized. If the tasks have already been loaded by `RakeCommand::perform` (but not memoized by `RakeCommand::rake_tasks`), then the tasks will be loaded a second time. This can cause, for example, constant redefinition warnings if the task files define constants. Therefore, this commit memoizes the tasks from `RakeCommand::perform` before raising `UnrecognizedCommandError`.
1 parent b368389 commit 455b8e4

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

railties/lib/rails/commands/rake/rake_command.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def printing_commands
1919
def perform(task, args, config)
2020
with_rake(task, *args) do |rake|
2121
if unrecognized_task = rake.top_level_tasks.find { |task| !rake.lookup(task[/[^\[]+/]) }
22+
@rake_tasks = rake.tasks
2223
raise UnrecognizedCommandError.new(unrecognized_task)
2324
end
2425

railties/test/command/help_integration_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,18 @@ class Rails::Command::HelpIntegrationTest < ActiveSupport::TestCase
1414
assert_match "Did you mean? version", output
1515
end
1616

17+
test "loads Rake tasks only once on unrecognized command" do
18+
app_file "lib/tasks/my_task.rake", <<~RUBY
19+
puts "MY_TASK already defined? => \#{!!defined?(MY_TASK)}"
20+
MY_TASK = true
21+
RUBY
22+
23+
output = rails "vershen", allow_failure: true
24+
25+
assert_match "MY_TASK already defined? => false", output
26+
assert_no_match "MY_TASK already defined? => true", output
27+
end
28+
1729
test "prints help via `X:help` command when running `X` and `X:X` command is not defined" do
1830
help = rails "dev:help"
1931
output = rails "dev", allow_failure: true

0 commit comments

Comments
 (0)