class RubbyCop::Cop::Rails::ReadWriteAttribute

This cop checks for the use of the read_attribute or write_attribute methods.

@example

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

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

Constants

MSG

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubbycop/cop/rails/read_write_attribute.rb, line 28
def on_send(node)
  return unless read_write_attribute?(node)

  add_offense(node, :selector)
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubbycop/cop/rails/read_write_attribute.rb, line 44
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
message(node) click to toggle source
# File lib/rubbycop/cop/rails/read_write_attribute.rb, line 36
def message(node)
  if node.method?(:read_attribute)
    format(MSG, 'self[:attr]', 'read_attribute(:attr)')
  else
    format(MSG, 'self[:attr] = val', 'write_attribute(:attr, val)')
  end
end
read_attribute_replacement(node) click to toggle source
# File lib/rubbycop/cop/rails/read_write_attribute.rb, line 55
def read_attribute_replacement(node)
  "self[#{node.first_argument.source}]"
end
write_attribute_replacement(node) click to toggle source
# File lib/rubbycop/cop/rails/read_write_attribute.rb, line 59
def write_attribute_replacement(node)
  "self[#{node.first_argument.source}] = #{node.last_argument.source}"
end