Skip to content

Commit

Permalink
fix to empty_when lint to ignore warns for 'when' with comments and e…
Browse files Browse the repository at this point in the history
…mpty lines
  • Loading branch information
kanth committed Nov 15, 2016
1 parent 8b3f72e commit 5870837
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
32 changes: 25 additions & 7 deletions lib/rubocop/cop/lint/empty_when.rb
Expand Up @@ -10,15 +10,11 @@ module Lint
# @bad
# case foo
# when bar then 1
# when baz then # nothing
# when baz
# end
class EmptyWhen < Cop
MSG = 'Avoid `when` branches without a body.'.freeze

def investigate(processed_source)
@processed_source = processed_source
end

def on_case(node)
_cond_node, *when_nodes, _else_node = *node

Expand All @@ -27,6 +23,10 @@ def on_case(node)
end
end

def comment_lines
@comment_lines ||= processed_source.comments.map{|comment| comment.loc.line}
end

private

def check_when(when_node)
Expand All @@ -35,8 +35,26 @@ def check_when(when_node)
end

def empty_when_body?(when_node)
node_comment = @processed_source[when_node.loc.first_line]
!(when_node.to_a.last || comment_line?(node_comment))
!when_node.to_a.last && no_comments?(when_node)
end

def no_comments?(when_node)
(comment_lines & line_range_to_next_node(when_node)).empty?
end

def line_range_to_next_node(node)
current_node_begin_line = node.loc.expression.begin.line
next_node_begin_line = if next_node(node)
next_node(node).loc.expression.begin.line
else
processed_source.lines.length
end
(current_node_begin_line..next_node_begin_line).to_a
end

def next_node(node)
return nil unless node.sibling_index > 0
node.parent.children[node.sibling_index + 1]
end
end
end
Expand Down
17 changes: 10 additions & 7 deletions spec/rubocop/cop/lint/empty_when_spec.rb
Expand Up @@ -47,13 +47,6 @@
'when :baz',
'end'].join("\n")

it_behaves_like 'code with offense',
['case foo',
'when :bar then 1',
'when :baz # nothing',
'else',
'end'].join("\n")

it_behaves_like 'code with offense',
['case foo',
'when :bar then 1',
Expand Down Expand Up @@ -142,5 +135,15 @@
'else',
' 3',
'end'].join("\n")
it_behaves_like 'code without offense',
['case',
'when :bar',
' 1',
'when :baz',
'',
' # nothing',
'else',
' 3',
'end'].join("\n")
end
end

0 comments on commit 5870837

Please sign in to comment.