Skip to content

Commit

Permalink
Tweak offense message for Lint/Void
Browse files Browse the repository at this point in the history
This commit tweaks offense message for `Lint/Void`
when registering offenses of void constants.
  • Loading branch information
koic authored and bbatsov committed Oct 25, 2023
1 parent 7bedbf4 commit 34e77c6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 9 deletions.
20 changes: 12 additions & 8 deletions lib/rubocop/cop/lint/void.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class Void < Base

OP_MSG = 'Operator `%<op>s` used in void context.'
VAR_MSG = 'Variable `%<var>s` used in void context.'
CONST_MSG = 'Constant `%<var>s` used in void context.'
LIT_MSG = 'Literal `%<lit>s` used in void context.'
SELF_MSG = '`self` used in void context.'
EXPRESSION_MSG = '`%<expression>s` used in void context.'
Expand Down Expand Up @@ -127,15 +128,18 @@ def check_void_op(node, &block)
def check_var(node)
return unless node.variable? || node.const_type?

if node.const_type? && node.special_keyword?
add_offense(node, message: format(VAR_MSG, var: node.source)) do |corrector|
autocorrect_void_expression(corrector, node)
end
if node.const_type?
template = node.special_keyword? ? VAR_MSG : CONST_MSG

offense_range = node
message = format(template, var: node.source)
else
add_offense(node.loc.name,
message: format(VAR_MSG, var: node.loc.name.source)) do |corrector|
autocorrect_void_expression(corrector, node)
end
offense_range = node.loc.name
message = format(VAR_MSG, var: node.loc.name.source)
end

add_offense(offense_range, message: message) do |corrector|
autocorrect_void_expression(corrector, node)
end
end

Expand Down
30 changes: 29 additions & 1 deletion spec/rubocop/cop/lint/void_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
end
end

%w[var @var @@var VAR $var].each do |var|
%w[var @var @@var $var].each do |var|
it "registers an offense for void var #{var} if not on last line" do
expect_offense(<<~RUBY, var: var)
%{var} = 5
Expand All @@ -101,6 +101,20 @@
end
end

it 'registers an offense for void constant `CONST` if not on last line' do
expect_offense(<<~RUBY)
CONST = 5
CONST
^^^^^ Constant `CONST` used in void context.
top
RUBY

expect_correction(<<~RUBY)
CONST = 5
top
RUBY
end

%w(1 2.0 :test /test/ [1] {}).each do |lit|
it "registers an offense for void lit #{lit} if not on last line" do
expect_offense(<<~RUBY, lit: lit)
Expand Down Expand Up @@ -437,6 +451,20 @@ def foo=(rhs)
RUBY
end

it 'registers an offenses for void constant in a `#each` method' do
expect_offense(<<~RUBY)
array.each do |_item|
CONST
^^^^^ Constant `CONST` used in void context.
end
RUBY

expect_correction(<<~RUBY)
array.each do |_item|
end
RUBY
end

it 'handles `#each` block with single expression' do
expect_offense(<<~RUBY)
array.each do |_item|
Expand Down

0 comments on commit 34e77c6

Please sign in to comment.