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

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/rails/read_write_attribute.rb

Overview

This cop 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.

Examples:


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

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

Constant Summary collapse

MSG =
'Prefer `%<prefer>s` over `%<current>s`.'

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/rails/read_write_attribute.rb', line 42

def autocorrect(node)
  case node.method_name
  when :read_attribute
    replacement = read_attribute_replacement(node)
  when :write_attribute
    replacement = write_attribute_replacement(node)
  end

  ->(corrector) { corrector.replace(node.source_range, replacement) }
end

#on_send(node) ⇒ Object



36
37
38
39
40
# File 'lib/rubocop/cop/rails/read_write_attribute.rb', line 36

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

  add_offense(node, location: :selector)
end