ActiveModel::AttributeMethods (original) (raw)

Active Model Attribute Methods

Provides a way to add prefixes and suffixes to your methods as well as handling the creation of ActiveRecord::Base - like class methods such as table_name.

The requirements to implement ActiveModel::AttributeMethods are to:

A minimal implementation could be:

class Person
  include ActiveModel::AttributeMethods

  attribute_method_affix  prefix: 'reset_', suffix: '_to_default!'
  attribute_method_suffix '_contrived?'
  attribute_method_prefix 'clear_'
  define_attribute_methods :name

  attr_accessor :name

  def attributes
    { 'name' => @name }
  end

  private
    def attribute_contrived?(attr)
      true
    end

    def clear_attribute(attr)
      send("#{attr}=", nil)
    end

    def reset_attribute_to_default!(attr)
      send("#{attr}=", 'Default Name')
    end
end

Namespace

Methods

A

M

R

Constants

CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/

Instance Public methods

attribute_missing is like method_missing, but for attributes. When method_missing is called we check to see if there is a matching attribute method. If so, we tell attribute_missing to dispatch the attribute. This method can be overloaded to customize the behavior.

Source: show | on GitHub

def attribute_missing(match, ...) send(match.proxy_target, match.attr_name, ...) end

Allows access to the object attributes, which are held in the hash returned by attributes, as though they were first-class methods. So a Person class with a name attribute can for example use Person#name and Person#name= and never directly use the attributes hash – except for multiple assignments with ActiveRecord::Base#attributes=.

It’s also possible to instantiate related objects, so a Client class belonging to the clients table with a master_id foreign key can instantiate master through Client#master.

Source: show | on GitHub

def method_missing(method, ...) if respond_to_without_attributes?(method, true) super else match = matched_attribute_method(method.name) match ? attribute_missing(match, ...) : super end end

Source: show | on GitHub

def respond_to?(method, include_private_methods = false) if super true elsif !include_private_methods && super(method, true)

false

else !matched_attribute_method(method.to_s).nil? end end

A Person instance with a name attribute can ask person.respond_to?(:name), person.respond_to?(:name=), and person.respond_to?(:name?) which will all return true.