Skip to content

Commit

Permalink
Rewrite Style/TrailingMethodEndStatement to make it faster
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima authored and bbatsov committed Jul 11, 2020
1 parent 94430a8 commit 19d534c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 40 deletions.
41 changes: 9 additions & 32 deletions lib/rubocop/cop/style/trailing_method_end_statement.rb
Expand Up @@ -33,22 +33,20 @@ module Style
# end
# end
#
class TrailingMethodEndStatement < Cop
include Alignment
class TrailingMethodEndStatement < Base
extend AutoCorrector

MSG = 'Place the end statement of a multi-line method on ' \
'its own line.'

def on_def(node)
return unless trailing_end?(node)

add_offense(node, location: end_token(node).pos)
end

def autocorrect(node)
lambda do |corrector|
break_line_before_end(node, corrector)
remove_semicolon(node, corrector)
add_offense(node.loc.end) do |corrector|
corrector.insert_before(
node.loc.end,
"\n" + ' ' * node.loc.keyword.column
)
end
end

Expand All @@ -60,30 +58,9 @@ def trailing_end?(node)
body_and_end_on_same_line?(node)
end

def end_token(node)
tokens(node).reverse.find(&:end?)
end

def body_and_end_on_same_line?(node)
end_token(node).line == token_before_end(node).line
end

def token_before_end(node)
i = tokens(node).index(end_token(node))
tokens(node)[i - 1]
end

def break_line_before_end(node, corrector)
corrector.insert_before(
end_token(node).pos,
"\n" + ' ' * configured_indentation_width
)
end

def remove_semicolon(node, corrector)
return unless token_before_end(node).semicolon?

corrector.remove(token_before_end(node).pos)
last_child = node.children.last
last_child.loc.last_line == node.loc.end.last_line
end
end
end
Expand Down
16 changes: 8 additions & 8 deletions spec/rubocop/cop/style/trailing_method_end_statement_spec.rb
Expand Up @@ -72,8 +72,8 @@ def some_method
RUBY
expect(corrected).to eq(<<~RUBY)
def some_method
[]
end
[];
end
RUBY
end

Expand All @@ -86,8 +86,8 @@ def do_this(x)
expect(corrected).to eq(<<~RUBY)
def do_this(x)
y = x + 5
y / 2
end
y / 2;
end
RUBY
end

Expand All @@ -101,7 +101,7 @@ def f(x, y)
def f(x, y)
process(x)
process(y)
end # comment
end # comment
RUBY
end

Expand All @@ -117,17 +117,17 @@ def d
block do
foo
end
end
end
RUBY
end

it 'auto-corrects all trailing ends for larger example' do
corrected = autocorrect_source(<<~RUBY)
class Foo
def some_method
[]; end
[] end
def another_method
{}; end
{} end
end
RUBY
expect(corrected).to eq(<<~RUBY)
Expand Down

0 comments on commit 19d534c

Please sign in to comment.