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

[Fix #1062] Correct rake tasks with arguments #1063

Merged
merged 1 commit into from
Aug 10, 2023
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1062](https://github.com/rubocop/rubocop-rails/issues/1062): Fix autocorrection for `Rails/RakeEnvironment` when rake task accepts arguments. ([@fastjames][])
24 changes: 20 additions & 4 deletions lib/rubocop/cop/rails/rake_environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,24 @@ def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return if with_dependencies?(task_method)

add_offense(task_method) do |corrector|
task_name = task_method.arguments[0]
task_dependency = correct_task_dependency(task_name)

corrector.replace(task_name, task_dependency)
if with_arguments?(task_method)
new_task_dependency = correct_task_arguments_dependency(task_method)
corrector.replace(task_arguments(task_method), new_task_dependency)
else
task_name = task_method.first_argument
new_task_dependency = correct_task_dependency(task_name)
corrector.replace(task_name, new_task_dependency)
end
end
end
end

private

def correct_task_arguments_dependency(task_method)
"#{task_arguments(task_method).source} => :environment"
end

def correct_task_dependency(task_name)
if task_name.sym_type?
"#{task_name.source.delete(':|\'|"')}: :environment"
Expand All @@ -80,6 +88,14 @@ def task_name(node)
end
end

def task_arguments(node)
node.arguments[1]
end

def with_arguments?(node)
node.arguments.size > 1 && node.arguments[1].array_type?
end

def with_dependencies?(node)
first_arg = node.arguments[0]
return false unless first_arg
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rails/rake_environment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@
RUBY
end

it 'registers an offense for a task with arguments' do
expect_offense(<<~RUBY)
task :foo, [:arg] do
^^^^^^^^^^^^^^^^^ Include `:environment` task as a dependency for all Rake tasks.
end
RUBY

expect_correction(<<~RUBY)
task :foo, [:arg] => :environment do
end
RUBY
end

it 'does not register an offense to task with :environment but it has other dependency before it' do
expect_no_offenses(<<~RUBY)
task foo: [:bar, `:environment`] do
Expand Down