From e5bd11114ef7012eff0ad1451dd43c291322162e Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Sat, 6 Aug 2022 00:21:30 -0400 Subject: [PATCH] [Fix #10877] Fix crash with `Layout/BlockEndNewline` heredoc detection. --- ...ix_fix_crash_with_layoutblockendnewline.md | 1 + lib/rubocop/cop/layout/block_end_newline.rb | 3 +- .../cop/layout/block_end_newline_spec.rb | 28 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_fix_crash_with_layoutblockendnewline.md diff --git a/changelog/fix_fix_crash_with_layoutblockendnewline.md b/changelog/fix_fix_crash_with_layoutblockendnewline.md new file mode 100644 index 00000000000..a1e4a21d7d5 --- /dev/null +++ b/changelog/fix_fix_crash_with_layoutblockendnewline.md @@ -0,0 +1 @@ +* [#10877](https://github.com/rubocop/rubocop/issues/10877): Fix crash with `Layout/BlockEndNewline` heredoc detection. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/layout/block_end_newline.rb b/lib/rubocop/cop/layout/block_end_newline.rb index 5cac3fb2997..625ccfa4a2b 100644 --- a/lib/rubocop/cop/layout/block_end_newline.rb +++ b/lib/rubocop/cop/layout/block_end_newline.rb @@ -60,9 +60,10 @@ def message(node) end def last_heredoc_argument(node) + return unless node&.call_type? return unless (arguments = node&.arguments) - heredoc = arguments.reverse.detect(&:heredoc?) + heredoc = arguments.reverse.detect { |arg| arg.str_type? && arg.heredoc? } return heredoc if heredoc last_heredoc_argument(node.children.first) diff --git a/spec/rubocop/cop/layout/block_end_newline_spec.rb b/spec/rubocop/cop/layout/block_end_newline_spec.rb index d28177c9371..51bdd3784ac 100644 --- a/spec/rubocop/cop/layout/block_end_newline_spec.rb +++ b/spec/rubocop/cop/layout/block_end_newline_spec.rb @@ -154,4 +154,32 @@ } RUBY end + + it 'registers an offense and corrects when a multiline block ends with a hash' do + expect_offense(<<~RUBY) + foo { + { bar: :baz } } + ^ Expression at 2, 17 should be on its own line. + RUBY + + expect_correction(<<~RUBY) + foo { + { bar: :baz } + } + RUBY + end + + it 'registers an offense and corrects when a multiline block ends with a method call with hash arguments' do + expect_offense(<<~RUBY) + foo { + bar(baz: :quux) } + ^ Expression at 2, 19 should be on its own line. + RUBY + + expect_correction(<<~RUBY) + foo { + bar(baz: :quux) + } + RUBY + end end