Skip to content

Commit

Permalink
[Fix rubocop#12404] Fix a false positive for `Layout/RescueEnsureAlig…
Browse files Browse the repository at this point in the history
…nment`

Fixes rubocop#12404.

This PR fixes a false positive for `Layout/RescueEnsureAlignment`
when aligned `rescue` in `do`-`end` numbered block in a method.
  • Loading branch information
koic committed Nov 22, 2023
1 parent 10c8d32 commit eebd60b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12404](https://github.com/rubocop/rubocop/issues/12404): Fix a false positive for `Layout/RescueEnsureAlignment` when aligned `rescue` in `do`-`end` numbered block in a method. ([@koic][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/layout/rescue_ensure_alignment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class RescueEnsureAlignment < Base
MSG = '`%<kw_loc>s` at %<kw_loc_line>d, %<kw_loc_column>d is not ' \
'aligned with `%<beginning>s` at ' \
'%<begin_loc_line>d, %<begin_loc_column>d.'
ANCESTOR_TYPES = %i[kwbegin def defs class module block].freeze
ANCESTOR_TYPES = %i[kwbegin def defs class module block numblock].freeze
ANCESTOR_TYPES_WITH_ACCESS_MODIFIERS = %i[def defs].freeze
ALTERNATIVE_ACCESS_MODIFIERS = %i[public_class_method private_class_method].freeze

Expand Down Expand Up @@ -95,7 +95,7 @@ def format_message(alignment_node, alignment_loc, kw_loc)
def alignment_source(node, starting_loc)
ending_loc =
case node.type
when :block, :kwbegin
when :block, :numblock, :kwbegin
node.loc.begin
when :def, :defs, :class, :module,
:lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn
Expand Down
39 changes: 39 additions & 0 deletions spec/rubocop/cop/layout/rescue_ensure_alignment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,45 @@ def foo
end
end

context 'Ruby 2.7', :ruby27 do
it 'accepts aligned rescue in do-end numbered block in a method' do
expect_no_offenses(<<~RUBY)
def foo
[1, 2, 3].each do
_1.to_s
rescue StandardError => _exception
next
end
end
RUBY
end

context 'rescue with do-end numbered block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foo
[1, 2, 3].each do
_1.to_s
rescue StandardError => _exception
^^^^^^ `rescue` at 4, 0 is not aligned with `[1, 2, 3].each do` at 2, 2.
next
end
end
RUBY

expect_correction(<<~RUBY)
def foo
[1, 2, 3].each do
_1.to_s
rescue StandardError => _exception
next
end
end
RUBY
end
end
end

context 'rescue in do-end block assigned to local variable' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit eebd60b

Please sign in to comment.