Class: RuboCop::Cop::Rails::ReadWriteAttribute

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

Overview

Checks for the use of the ‘read_attribute` or `write_attribute` methods and recommends square brackets instead.

If an attribute is missing from the instance (for example, when initialized by a partial ‘select`) then `read_attribute` will return nil, but square brackets will raise an `ActiveModel::MissingAttributeError`.

Explicitly raising an error in this situation is preferable, and that is why rubocop recommends using square brackets.

When called from within a method with the same name as the attribute, ‘read_attribute` and `write_attribute` must be used to prevent an infinite loop:

Examples:


# bad
x = read_attribute(:attr)
write_attribute(:attr, val)

# good
x = self[:attr]
self[:attr] = val

# good
def foo
  bar || read_attribute(:foo)
end

Constant Summary collapse

MSG =
'Prefer `%<prefer>s`.'
RESTRICT_ON_SEND =
%i[read_attribute write_attribute].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/rails/read_write_attribute.rb', line 50

def on_send(node)
  return unless read_write_attribute?(node)
  return if within_shadowing_method?(node)

  add_offense(node, message: build_message(node)) do |corrector|
    corrector.replace(node, node_replacement(node))
  end
end