module AttributeMethods

Ruby on Rails 3.0.20

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Active Model Attribute Methods

ActiveModel::AttributeMethods provides a way to add prefixes and suffixes to your methods as well as handling the creation of Active Record like class methods such as table_name.

The requirements to implement ActiveModel::AttributeMethods are to:

  • include ActiveModel::AttributeMethods in your object

  • Call each Attribute Method module method you want to add, such as attribute_method_suffix or attribute_method_prefix

  • Call define_attribute_methods after the other methods are called.

  • Define the various generic _attribute methods that you have declared

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

  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

Note that whenever you include ActiveModel::AttributeMethods in your class, it requires you to implement an attributes method which returns a hash with each attribute name in your model as hash key and the attribute value as hash value.

Hash keys must be strings.

Namespace

Modules

Extends

Constants

Methods (defined here)

Private methods

(3) Implementation detail — not part of the public API.

Used by

Included by (1)

Methods (inherited)

From ActiveSupport::Concern (3)

Type at least 2 characters to search.

↑↓ navigate · open · esc close