Check blocks with _1 and it in AvoidReturnFromBlocks

What does this MR do?

Makes Cop/AvoidReturnFromBlocks check blocks that use numbered parameters (_1) or Ruby 3.4's it, which it skipped until now.

Related to #94 (closed). !294 (merged) fixes RSpec/ExampleStartingCharacter the same way.

call { |a| return if a }  # offense, before and after
call { return if _1 }     # offense only after this MR
call { return if it }     # offense only after this MR
Cause and fix
  • The cop sends numblock and itblock nodes to on_block, but top_block? and parent_blocks only treated block nodes as blocks. So top_block? returned false for a _1 or it block, and on_block returned before looking for return.
  • def? had the same check, so a lambda or define_method block using _1 or it wasn't treated as a definition. Nested in another block, its return was flagged, for example helpers { define_method(:x) { return if _1 } }.
  • The fix uses any_block_type? in all three places.
Specs

The new examples run with _1, and with it under :ruby34. Against master's version of the cop, 8 of them fail: the two offense cases and the two nested lambda and define_method cases, for each parameter.

Impact: projects using gitlab-styles may get new offenses for return in _1 or it blocks.

Edited by Abdul Wadood

Merge request reports

Loading
Loading