diff --git a/lib/rubocop/cop/style/trailing_method_end_statement.rb b/lib/rubocop/cop/style/trailing_method_end_statement.rb index a49d0d1349f..d4f3309eb20 100644 --- a/lib/rubocop/cop/style/trailing_method_end_statement.rb +++ b/lib/rubocop/cop/style/trailing_method_end_statement.rb @@ -33,8 +33,8 @@ 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.' @@ -42,13 +42,11 @@ class TrailingMethodEndStatement < Cop 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 @@ -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 diff --git a/spec/rubocop/cop/style/trailing_method_end_statement_spec.rb b/spec/rubocop/cop/style/trailing_method_end_statement_spec.rb index 58a17b2bd28..1b9abe62d29 100644 --- a/spec/rubocop/cop/style/trailing_method_end_statement_spec.rb +++ b/spec/rubocop/cop/style/trailing_method_end_statement_spec.rb @@ -72,8 +72,8 @@ def some_method RUBY expect(corrected).to eq(<<~RUBY) def some_method - [] - end + []; + end RUBY end @@ -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 @@ -101,7 +101,7 @@ def f(x, y) def f(x, y) process(x) process(y) - end # comment + end # comment RUBY end @@ -117,7 +117,7 @@ def d block do foo end - end + end RUBY end @@ -125,9 +125,9 @@ def d corrected = autocorrect_source(<<~RUBY) class Foo def some_method - []; end + [] end def another_method - {}; end + {} end end RUBY expect(corrected).to eq(<<~RUBY)