модуль ActiveModel::Conversion
Преобразование Active Model
Обрабатывает стандартные преобразования: to_model, to_key, to_param и to_partial_path.
Рассмотрим, например, этот непродолжительный объект.
class ContactMessage
include ActiveModel::Conversion
# ContactMessage are never persisted in the DB
def persisted?
false
end
end
cm = ContactMessage.new
cm.to_model == cm # => true
cm.to_key # => nil
cm.to_param # => nil
cm.to_partial_path # => "contact_messages/contact_message"
Методы экземпляра общедоступного использования
# File activemodel/lib/active_model/conversion.rb, line 59 def to_key key = respond_to?(:id) && id key ? [key] : nil end
Возвращает Array всех ключевых атрибутов, если какой-либо из атрибутов установлен, вне зависимости от того, сохранен ли объект. Возвращает nil, если ключевых атрибутов нет.
class Person
include ActiveModel::Conversion
attr_accessor :id
def initialize(id)
@id = id
end
end
person = Person.new(1)
person.to_key # => [1]
# File activemodel/lib/active_model/conversion.rb, line 41 def to_model self end
Если ваш объект уже разработан для реализации всех функций Active Model, вы можете использовать стандартную реализацию :to_model, которая просто возвращает self.
class Person include ActiveModel::Conversion end person = Person.new person.to_model == person # => true
Если ваш объект не действует как объект Active Model, вы должны определить :to_model сами, вернув прокси-объект, который обернёт ваш объект методами, совместимыми с Active Model.
# File activemodel/lib/active_model/conversion.rb, line 82
def to_param
(persisted? && key = to_key) ? key.join("-") : nil
end Возвращает string, представляющий ключевые атрибуты объекта, подходящий для использования в URL-адресах, или nil, если persisted? false.
class Person
include ActiveModel::Conversion
attr_accessor :id
def initialize(id)
@id = id
end
def persisted?
true
end
end
person = Person.new(1)
person.to_param # => "1"
# File activemodel/lib/active_model/conversion.rb, line 95 def to_partial_path self.class._to_partial_path end
Возвращает string, идентифицирующий путь, связанный с объектом. ActionPack использует это для поиска подходящей части для представления объекта.
class Person include ActiveModel::Conversion end person = Person.new person.to_partial_path # => "people/person"
© 2004–2020 David Heinemeier Hansson
Licensed under the MIT License.