Skip to content

Commit

Permalink
Merge pull request #1063 from fastjames/rake_environment_autocorrect_…
Browse files Browse the repository at this point in the history
…args

[Fix #1062] Correct rake tasks with arguments
  • Loading branch information
koic authored Aug 10, 2023
2 parents 6202d3e + dd17d2d commit fc1be54
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
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

0 comments on commit fc1be54

Please sign in to comment.