diff --git a/changelog/fix_an_error_for_empty_lines_around_exception_handling_keywords.md b/changelog/fix_an_error_for_empty_lines_around_exception_handling_keywords.md new file mode 100644 index 00000000000..e457e659a6e --- /dev/null +++ b/changelog/fix_an_error_for_empty_lines_around_exception_handling_keywords.md @@ -0,0 +1 @@ +* [#10193](https://github.com/rubocop/rubocop/pull/10193): Fix an error for `Layout/EmptyLinesAroundExceptionHandlingKeywords` when `begin` and `rescue` are on the same line. ([@koic][]) diff --git a/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb b/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb index 40abfb0040b..97c950b48b5 100644 --- a/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb +++ b/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb @@ -65,21 +65,24 @@ class EmptyLinesAroundExceptionHandlingKeywords < Base MSG = 'Extra empty line detected %s the `%s`.' def on_def(node) - check_body(node.body) + check_body(node.body, node.loc.line) end alias on_defs on_def def on_kwbegin(node) body, = *node - check_body(body) + check_body(body, node.loc.line) end private - def check_body(node) - locations = keyword_locations(node) + def check_body(body, line_of_def_or_kwbegin) + locations = keyword_locations(body) + locations.each do |loc| line = loc.line + next if line == line_of_def_or_kwbegin + keyword = loc.source # below the keyword check_line(style, line, message('after', keyword), &:empty?) diff --git a/spec/rubocop/cop/layout/empty_lines_around_exception_handling_keywords_spec.rb b/spec/rubocop/cop/layout/empty_lines_around_exception_handling_keywords_spec.rb index 73d5a4499db..46d2d8eede3 100644 --- a/spec/rubocop/cop/layout/empty_lines_around_exception_handling_keywords_spec.rb +++ b/spec/rubocop/cop/layout/empty_lines_around_exception_handling_keywords_spec.rb @@ -127,6 +127,14 @@ def foo end RUBY + include_examples 'accepts', '`begin` and `rescue` are on the same line', <<~RUBY + begin; foo; rescue => e; end + RUBY + + include_examples 'accepts', '`def` and `rescue` are on the same line', <<~RUBY + def do_something; foo; rescue => e; end + RUBY + it 'with complex begin-end - registers many offenses' do expect_offense(<<~RUBY) begin