jsonapi-serializers icon indicating copy to clipboard operation
jsonapi-serializers copied to clipboard

Customize attributes by any callable object

Open ZurgInq opened this issue 7 years ago • 2 comments

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

ZurgInq avatar Apr 15 '17 05:04 ZurgInq

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?

mwpastore avatar Apr 15 '17 06:04 mwpastore

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

whatthewhat avatar Jul 17 '17 11:07 whatthewhat