модуль ActiveModel::AttributeMethods
Методы атрибутов Active Model
Позволяет добавлять к методам префиксы и суффиксы, а также обрабатывать создание методов класса, подобных ActiveRecord::Base, например table_name.
Чтобы реализовать ActiveModel::AttributeMethods, необходимо:
-
include ActiveModel::AttributeMethodsв вашем классе. -
Вызвать каждый из методов, которые вы хотите добавить, например
attribute_method_suffixилиattribute_method_prefix. -
Вызвать
define_attribute_methodsпосле вызова остальных методов. -
Определить различные универсальные методы
_attribute, объявленные вами. -
Определить метод
attributes, который возвращает хеш, где имя каждого атрибута модели является ключом, а значение атрибута — значением. КлючиHashдолжны быть строками.
Минимальная реализация может выглядеть так:
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
Константы
- CALL_COMPILABLE_REGEXP
- NAME_COMPILABLE_REGEXP
Открытые методы экземпляра
# File activemodel/lib/active_model/attribute_methods.rb, line 520 def attribute_missing(match, ...) __send__(match.proxy_target, match.attr_name, ...) end
attribute_missing похож на method_missing, но предназначен для атрибутов. Когда вызывается method_missing, мы проверяем, существует ли соответствующий метод атрибута. Если да, мы указываем attribute_missing обработать атрибут. Этот метод можно переопределить, чтобы настроить поведение.
# File activemodel/lib/active_model/attribute_methods.rb, line 507
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 Позволяет обращаться к атрибутам объекта, хранящимся в хеше, возвращаемом методом attributes, как к полноценным методам. Например, класс Person с атрибутом name может использовать Person#name и Person#name=, не обращаясь напрямую к хешу атрибутов — за исключением множественного присваивания с помощью ActiveRecord::Base#attributes=.
Также можно создавать связанные объекты: например, класс Client, связанный с таблицей clients и имеющий внешний ключ master_id, может создать главный объект с помощью Client#master.
# File activemodel/lib/active_model/attribute_methods.rb, line 528
def respond_to?(method, include_private_methods = false)
if super
true
elsif !include_private_methods && super(method, true)
# If we're here then we haven't found among non-private methods
# but found among all methods. Which means that the given method is private.
false
else
!matched_attribute_method(method.to_s).nil?
end
end Экземпляр Person с атрибутом name может вызвать person.respond_to?(:name), person.respond_to?(:name=) и person.respond_to?(:name?); все они вернут true.
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.