модуль ActiveModel::AttributeMethods
Методы атрибутов Active Model
Предоставляет способ добавления префиксов и суффиксов к вашим методам, а также обработки создания методов класса, подобных ActiveRecord::Base и table_name.
Для реализации ActiveModel::AttributeMethods необходимо:
-
include ActiveModel::AttributeMethodsв вашем классе. -
Вызвать каждый из его методов, которые вы хотите добавить, например
attribute_method_suffixилиattribute_method_prefix. -
Вызвать
define_attribute_methodsпосле вызова других методов. -
Определить различные общие методы
_attribute, которые вы объявили. -
Определить метод
attributes, который возвращает хэш, где ключами являются имена атрибутов вашей модели, а значениями — значения атрибутов. Ключи хэша должны быть строками. Хэш
Минимальная реализация может быть такой:
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 439 def attribute_missing(match, *args, &block) __send__(match.target, match.attr_name, *args, &block) end
attribute_missing подобен method_missing, но для атрибутов. Когда вызывается method_missing, мы проверяем, существует ли соответствующий метод атрибута. Если да, мы говорим attribute_missing о диспетчеризации атрибута. Этот метод можно переопределить, чтобы настроить поведение.
# File activemodel/lib/active_model/attribute_methods.rb, line 426
def method_missing(method, *args, &block)
if respond_to_without_attributes?(method, true)
super
else
match = matched_attribute_method(method.to_s)
match ? attribute_missing(match, *args, &block) : 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 447
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–2019 David Heinemeier Hansson
Licensed under the MIT License.