jsonapi-serializers
jsonapi-serializers copied to clipboard
Customize attributes by any callable object
example:
class ToISO8601
def self.call(obj)
obj.iso8601
end
end
# or ToISO8601 = ->(obj) { obj.iso8601 }
class PostSerializer
include JSONAPI::Serializer
attribute :created_at, ToISO8601
attribute :updated_at, ToISO8601
# or by lambda
# attribute :updated_at, ->(obj) { obj.iso8601 }
end
I think this would be a useful feature, but as temporary workarounds, these work fine:
attribute :created_at, &:iso8601
attribute :created_at, &->(obj) { obj.iso8601 }
attribute :created_at, &ToISO8601.method(:call) # yuck
Are you planning to submit a PR?
Just a quick note that the workarounds above do not seem to work since the argument that is passed to the proc is a serializer instance, not the attribute (resulting in undefined method 'iso8601' for #<FooSerializer:0x000000051ea2a8
).
Here's what I ended up using for date attributes:
class BaseSerializer
include JSONAPI::Serializer
def self.date_attribute(name)
attribute(name) do
value = object.public_send(name)
value.respond_to?(:iso8601) ? value.iso8601 : value
end
end
end
class FooSerializer < BaseSerializer
date_attribute :created_at
# other attributes...
end