Skip to content

Commit

Permalink
Merge pull request #11659 from koic/fix_incorrect_autocorrect_for_lin…
Browse files Browse the repository at this point in the history
…t_or_assignment_to_constant

Fix an incorrect autocorrect for `Lint/OrAssignmentToConstant`
  • Loading branch information
koic committed Mar 4, 2023
2 parents 046cc54 + 1f4b6b4 commit 7f96a01
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11659](https://github.com/rubocop/rubocop/pull/11659): Fix an incorrect autocorrect for `Lint/OrAssignmentToConstant` when using or-assignment to a constant in method definition. ([@koic][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/lint/or_assignment_to_constant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ def on_or_asgn(node)
return unless lhs&.casgn_type?

add_offense(node.loc.operator) do |corrector|
next if node.each_ancestor(:def, :defs).any?

corrector.replace(node.loc.operator, '=')
end
end
Expand Down
37 changes: 37 additions & 0 deletions spec/rubocop/cop/lint/or_assignment_to_constant_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,43 @@
RUBY
end

it 'registers an offense with or-assignment to a constant in method definition' do
expect_offense(<<~RUBY)
def foo
M::CONST ||= 1
^^^ Avoid using or-assignment with constants.
end
RUBY

expect_no_corrections
end

it 'registers an offense with or-assignment to a constant in singleton method definition' do
expect_offense(<<~RUBY)
def self.foo
M::CONST ||= 1
^^^ Avoid using or-assignment with constants.
end
RUBY

expect_no_corrections
end

it 'registers an offense with or-assignment to a constant in method definition using `define_method`' do
expect_offense(<<~RUBY)
define_method :foo do
M::CONST ||= 1
^^^ Avoid using or-assignment with constants.
end
RUBY

expect_correction(<<~RUBY)
define_method :foo do
M::CONST = 1
end
RUBY
end

it 'does not register an offense with plain assignment to a constant' do
expect_no_offenses(<<~RUBY)
CONST = 1
Expand Down

0 comments on commit 7f96a01

Please sign in to comment.