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

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:

  • include ActiveModel::AttributeMethods in your class.

  • Call each of its 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.

  • Define 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.

A minimal implementation could be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
attribute_missing
  • References/Ruby on Rails/Rails/Classes/ActiveModel/ActiveModel::AttributeMethods

attribute_missing(match, *args, &block) Instance Public methods a

2025-01-10 15:47:30
undefine_attribute_methods
  • References/Ruby on Rails/Rails/Classes/ActiveModel/ActiveModel::AttributeMethods/ActiveModel::AttributeMethods::ClassMethods

undefine_attribute_methods() Instance Public methods Removes all the previously

2025-01-10 15:47:30
method_missing
  • References/Ruby on Rails/Rails/Classes/ActiveModel/ActiveModel::AttributeMethods

method_missing(method, *args, &block) Instance Public methods Allows access

2025-01-10 15:47:30