Как визуализировать атрибут, только если какое-то условие истинно?
Например, я хочу показать атрибут User token для создания действия.
Как визуализировать атрибут, только если какое-то условие истинно?
Например, я хочу показать атрибут User token для создания действия.
Вы также можете сделать это следующим образом:
class EntitySerializer < ActiveModel::Serializer
attributes :id, :created_at, :updated_at
attribute :conditional_attr, if: :condition?
def condition?
#condition code goes here
end
end
Например:
class UserSerializer < ActiveModel::Serializer
attributes :id, :username, :name, :email, :created_at, :updated_at
attribute :auth_token, if: :auth_token?
def created_at
object.created_at.to_i
end
def updated_at
object.updated_at.to_i
end
def auth_token?
true if object.auth_token
end
end
Подробнее см. .
вы можете переопределить метод attributes, вот простой пример:
class Foo < ActiveModel::Serializer
attributes :id
def attributes(*args)
hash = super
hash[:last_name] = 'Bob' unless object.persisted?
hash
end
end
Вы можете начать с установки условия для метода инициализации сериализатора. Это условие может быть передано из любого места в вашем коде, включенного в хэш-параметры, который "инициализирует" принимает в качестве второго аргумента:
class SomeCustomSerializer < ActiveModel::Serializer
attributes :id, :attr1, :conditional_attr2, :conditional_attr2
def initialize(object, options={})
@condition = options[:condition].present? && options[:condition]
super(object, options)
end
def attributes(*args)
return super unless @condition #get all the attributes
attributes_to_remove = [:conditional_attr2, :conditional_attr2]
filtered = super.except(*attributes_to_remove)
filtered
end
end
В этом случае attr1 всегда будет передан, а условные атрибуты будут скрыты, если условие истинно.
Вы получите результат этой пользовательской сериализации, где бы вы ни находились в вашем коде:
custom_serialized_object = SomeCustomSerializer.new(object_to_serialize, {:condition => true})
Надеюсь, это было полезно!
Сериализатор параметры были объединены в сериализаторы ActiveModel и теперь доступны (начиная с 0.10).
Переопределение - хорошая идея, но если вы используете super, атрибуты будут вычисляться до того, как вы удалите то, что хотите. Если это не имеет для вас значения, хорошо, но когда это произойдет, вы можете использовать его:
def attributes(options={})
attributes =
if options[:fields]
self.class._attributes & options[:fields]
else
self.class._attributes.dup
end
attributes.delete_if {|attr| attr == :attribute_name } if condition
attributes.each_with_object({}) do |name, hash|
unless self.class._fragmented
hash[name] = send(name)
else
hash[name] = self.class._fragmented.public_send(name)
end
end
end
ps: v0.10.0.rc3