From 5870837479f4815e6aeb755fe0c1fac0f466a117 Mon Sep 17 00:00:00 2001 From: Hanumakanth Date: Fri, 11 Nov 2016 16:56:54 +0530 Subject: [PATCH] fix to empty_when lint to ignore warns for 'when' with comments and empty lines --- lib/rubocop/cop/lint/empty_when.rb | 32 ++++++++++++++++++------ spec/rubocop/cop/lint/empty_when_spec.rb | 17 +++++++------ 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/lib/rubocop/cop/lint/empty_when.rb b/lib/rubocop/cop/lint/empty_when.rb index 9a0676a5c37..8c93643fbba 100644 --- a/lib/rubocop/cop/lint/empty_when.rb +++ b/lib/rubocop/cop/lint/empty_when.rb @@ -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 @@ -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) @@ -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 diff --git a/spec/rubocop/cop/lint/empty_when_spec.rb b/spec/rubocop/cop/lint/empty_when_spec.rb index 836dff53920..c462e6b65a3 100644 --- a/spec/rubocop/cop/lint/empty_when_spec.rb +++ b/spec/rubocop/cop/lint/empty_when_spec.rb @@ -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', @@ -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