Skip to content

Commit

Permalink
Improve offense message for Style/YodaExpression cop
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima authored and bbatsov committed Dec 31, 2022
1 parent d4aeaf1 commit 32e13c5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions lib/rubocop/cop/style/yoda_expression.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module Style
class YodaExpression < Base
extend AutoCorrector

MSG = 'Non literal operand should be first.'
MSG = 'Non-literal operand (`%<source>s`) should be first.'

RESTRICT_ON_SEND = %i[* + & | ^].freeze

Expand All @@ -47,12 +47,12 @@ def on_send(node)

return if offended_ancestor?(node)

add_offense(node) do |corrector|
message = format(MSG, source: rhs.source)
add_offense(node, message: message) do |corrector|
corrector.swap(lhs, rhs)
end

@offended_nodes ||= Set.new.compare_by_identity
@offended_nodes.add(node)
offended_nodes.add(node)
end

private
Expand All @@ -64,6 +64,10 @@ def supported_operators
def offended_ancestor?(node)
node.each_ancestor(:send).any? { |ancestor| @offended_nodes&.include?(ancestor) }
end

def offended_nodes
@offended_nodes ||= Set.new.compare_by_identity
end
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions spec/rubocop/cop/style/yoda_expression_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
it 'registers an offense when using simple offended example' do
expect_offense(<<~RUBY)
1 + x
^^^^^ Non literal operand should be first.
^^^^^ Non-literal operand (`x`) should be first.
RUBY

expect_correction(<<~RUBY)
Expand All @@ -17,7 +17,7 @@
it 'registers an offense and corrects when using complex offended example' do
expect_offense(<<~RUBY)
2 + (1 + x)
^^^^^^^^^^^ Non literal operand should be first.
^^^^^^^^^^^ Non-literal operand (`(1 + x)`) should be first.
RUBY

expect_correction(<<~RUBY)
Expand Down

0 comments on commit 32e13c5

Please sign in to comment.