Skip to content

Commit

Permalink
[Fix rubocop#1041] Fix a false positive for Rails/Output
Browse files Browse the repository at this point in the history
Fixes rubocop#1041.

This PR fixes a false positive for `Rails/Output`
when output method is called with block argument.

The output method for the bad case is not designed to take a block argument.
Thus, by ignoring this, it can likely reduce false positives.
  • Loading branch information
koic committed Oct 5, 2023
1 parent 6051d88 commit 6f72227
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_a_false_positive_for_rails_output.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1041](https://github.com/rubocop/rubocop-rails/issues/1041): Fix a false positive for `Rails/Output` when output method is called with block argument. ([@koic][])
5 changes: 3 additions & 2 deletions lib/rubocop/cop/rails/output.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Output < Base

MSG = "Do not write to stdout. Use Rails's logger if you want to log."
RESTRICT_ON_SEND = %i[ap p pp pretty_print print puts binwrite syswrite write write_nonblock].freeze
ALLOWED_TYPES = %i[send csend block numblock].freeze

def_node_matcher :output?, <<~PATTERN
(send nil? {:ap :p :pp :pretty_print :print :puts} ...)
Expand All @@ -39,8 +40,8 @@ class Output < Base
PATTERN

def on_send(node)
return if node.parent&.call_type?
return unless output?(node) || io_output?(node)
return if ALLOWED_TYPES.include?(node.parent&.type)
return if !output?(node) && !io_output?(node)

range = offense_range(node)

Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/rails/output_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,27 @@
RUBY
end

it 'does not register an offense when the `p` method is called with block argument' do
expect_no_offenses(<<~RUBY)
# phlex-rails gem.
div do
p { 'Some text' }
end
RUBY
end

it 'does not register an offense when io method is called with block argument' do
expect_no_offenses(<<~RUBY)
obj.write { do_somethig }
RUBY
end

it 'does not register an offense when io method is called with numbered block argument' do
expect_no_offenses(<<~RUBY)
obj.write { do_something(_1) }
RUBY
end

it 'does not register an offense when a method is ' \
'safe navigation called to a local variable with the same name as a print method' do
expect_no_offenses(<<~RUBY)
Expand Down

0 comments on commit 6f72227

Please sign in to comment.