Skip to content

Commit

Permalink
[Fix rubocop#2124] Look for empty lines between defs
Browse files Browse the repository at this point in the history
Checking if there are actually empty lines between defs instead of
looking for any lines between `def` nodes.
  • Loading branch information
unmanbearpig committed Aug 12, 2015
1 parent fd6a66f commit eb37a68
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 9 deletions.
36 changes: 27 additions & 9 deletions lib/rubocop/cop/style/empty_line_between_defs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,38 @@ class EmptyLineBetweenDefs < Cop
MSG = 'Use empty lines between defs.'

def on_def(node)
if @prev_def_end && (def_start(node) - @prev_def_end) == 1
unless @prev_was_single_line && singe_line_def?(node) &&
cop_config['AllowAdjacentOneLineDefs']
add_offense(node, :keyword)
end
end
nodes = [prev_node(node), node]

return unless nodes.all?(&method(:def_node?))
return if blank_lines_between?(*nodes)

@prev_def_end = def_end(node)
@prev_was_single_line = singe_line_def?(node)
unless nodes.all?(&method(:single_line_def?)) &&
cop_config['AllowAdjacentOneLineDefs']
add_offense(node, :keyword)
end
end

private

def singe_line_def?(node)
def def_node?(node)
node && node.type == :def
end

def blank_lines_between?(first_def_node, second_def_node)
lines_between_defs(first_def_node, second_def_node).any?(&:empty?)
end

def prev_node(node)
return nil unless node.parent && node.sibling_index > 0

node.parent.children[node.sibling_index-1]
end

def lines_between_defs first_def_node, second_def_node
processed_source.lines[def_end(first_def_node)..def_start(second_def_node)-2]
end

def single_line_def?(node)
def_start(node) == def_end(node)
end

Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/cop/style/empty_line_between_defs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,30 @@
' def b; end'].join("\n"))
end

it 'finds offenses for adjacent multi-liners' do
source = [' class J',
' def n',
' end',
' def o',
' end',
' end']
inspect_source(cop, source)
expect(cop.offenses.size).to eq(1)
end

it 'finds offenses for adjacent multi-liners with comments' do
source = [' class J',
' # checks something n-related',
' def n',
' end',
' # checks something o-related',
' def o',
' end',
' end']
inspect_source(cop, source)
expect(cop.offenses.size).to eq(1)
end

context 'when AllowAdjacentOneLineDefs is enabled' do
let(:cop_config) { { 'AllowAdjacentOneLineDefs' => true } }

Expand Down

0 comments on commit eb37a68

Please sign in to comment.