Class: RuboCop::Cop::Rails::RedundantReceiverInWithOptions

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/redundant_receiver_in_with_options.rb

Overview

This cop checks for redundant receiver in `with_options`. Receiver is implicit from Rails 4.2 or higher.

Examples:

# bad
class Account < ApplicationRecord
  with_options dependent: :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end

# good
class Account < ApplicationRecord
  with_options dependent: :destroy do
    has_many :customers
    has_many :products
    has_many :invoices
    has_many :expenses
  end
end
# bad
with_options options: false do |merger|
  merger.invoke(merger.something)
end

# good
with_options options: false do
  invoke(something)
end

# good
client = Client.new
with_options options: false do |merger|
  client.invoke(merger.something, something)
end

# ok
# When `with_options` includes a block, all scoping scenarios
# cannot be evaluated. Thus, it is ok to include the explicit
# receiver.
with_options options: false do |merger|
  merger.invoke
  with_another_method do |another_receiver|
    merger.invoke(another_receiver)
  end
end

Constant Summary collapse

MSG =
'Redundant receiver in `with_options`.'

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rubocop/cop/rails/redundant_receiver_in_with_options.rb', line 80

def on_block(node)
  with_options?(node) do |arg, body|
    return if body.nil?
    return unless all_block_nodes_in(body).count.zero?

    send_nodes = all_send_nodes_in(body)

    if send_nodes.all? { |n| same_value?(arg, n.receiver) }
      send_nodes.each do |send_node|
        receiver = send_node.receiver
        add_offense(receiver.source_range) do |corrector|
          autocorrect(corrector, send_node)
        end
      end
    end
  end
end