define_attribute_method(attr_name) public

Declares an attribute that should be prefixed and suffixed by ActiveModel::AttributeMethods.

To use, pass an attribute name (as string or symbol), be sure to declare define_attribute_method after you define any prefix, suffix or affix method, or they will not hook in.

class Person
  include ActiveModel::AttributeMethods

  attr_accessor :name
  attribute_method_suffix '_short?'

  # Call to define_attribute_method must appear after the
  # attribute_method_prefix, attribute_method_suffix or
  # attribute_method_affix declares.
  define_attribute_method :name

  private

  def attribute_short?(attr)
    send(attr).length < 5
  end
end

person = Person.new
person.name = 'Bob'
person.name        # => "Bob"
person.name_short? # => true
Show source
Register or log in to add new notes.