Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #9973] Fix a false positive for Layout/RescueEnsureAlignment #9974

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#9973](https://github.com/rubocop/rubocop/issues/9973): Fix a false positive for `Layout/RescueEnsureAlignment` when aligned `rescue` keyword and leading dot. ([@koic][])
20 changes: 20 additions & 0 deletions lib/rubocop/cop/layout/rescue_ensure_alignment.rb
Expand Up @@ -117,6 +117,8 @@ def alignment_node(node)
ancestor_node = ancestor_node(node)

return ancestor_node if ancestor_node.nil? || ancestor_node.kwbegin_type?
return if ancestor_node.respond_to?(:send_node) &&
aligned_with_line_break_method?(ancestor_node, node)

assignment_node = assignment_node(ancestor_node)
return assignment_node if same_line?(ancestor_node, assignment_node)
Expand All @@ -131,6 +133,24 @@ def ancestor_node(node)
node.each_ancestor(*ANCESTOR_TYPES).first
end

def aligned_with_line_break_method?(ancestor_node, node)
send_node_loc = ancestor_node.send_node.loc
do_keyword_line = ancestor_node.loc.begin.line
rescue_keyword_column = node.loc.keyword.column
selector = send_node_loc.selector

if send_node_loc.respond_to?(:dot) && (dot = send_node_loc.dot) &&
aligned_with_leading_dot?(do_keyword_line, dot, rescue_keyword_column)
return true
end

do_keyword_line == selector.line && rescue_keyword_column == selector.column
end

def aligned_with_leading_dot?(do_keyword_line, dot, rescue_keyword_column)
do_keyword_line == dot.line && rescue_keyword_column == dot.column
end

def assignment_node(node)
assignment_node = node.ancestors.first
return nil unless
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/layout/rescue_ensure_alignment_spec.rb
Expand Up @@ -449,6 +449,28 @@ def foo
RUBY
end

it 'accepts aligned rescue with do-end block that line break with leading dot for method calls' do
expect_no_offenses(<<~RUBY)
[1, 2, 3]
.each do |el|
el.to_s
rescue StandardError => _exception
next
end
RUBY
end

it 'accepts aligned rescue with do-end block that line break with trailing dot for method calls' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].
each do |el|
el.to_s
rescue StandardError => _exception
next
end
RUBY
end

it 'accepts aligned rescue do-end block assigned to local variable' do
expect_no_offenses(<<~RUBY)
result = [1, 2, 3].map do |el|
Expand Down