I want to use a serializer that renders not null attributes
class PersonSerializer < ActiveModel::Serializer
attributes :id, :name, :phone, :address, :email
end
Is this possible.
Many thanks.
Solution:
class PersonSerializer < ActiveModel::Serializer
attributes :id, :name, :phone, :address, :email
def attributes
hash = super
hash.each {|key, value|
if value.nil?
hash.delete(key)
end
}
hash
end
end
From version 0.10.x of active_model_serializer
gem, you have to override the method serializable_hash
instead of attributes
:
# place this method inside NullAttributesRemover or directly inside serializer class
def serializable_hash(adapter_options = nil, options = {}, adapter_instance = self.class.serialization_adapter_instance)
hash = super
hash.each { |key, value| hash.delete(key) if value.nil? }
hash
end
Thanks Nabila Hamdaoui for your solution. I made it a little more reusable via modules.
null_attribute_remover.rb
module NullAttributesRemover
def attributes
hash = super
hash.each do |key, value|
if value.nil?
hash.delete(key)
end
end
hash
end
end
Usage:
swimlane_serializer.rb
class SwimlaneSerializer < ActiveModel::Serializer
include NullAttributesRemover
attributes :id, :name, :wipMaxLimit
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With