Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customize attributes by any callable object #105

Open
ZurgInq opened this issue Apr 15, 2017 · 2 comments
Open

Customize attributes by any callable object #105

ZurgInq opened this issue Apr 15, 2017 · 2 comments

Comments

@ZurgInq
Copy link

ZurgInq commented Apr 15, 2017

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
@mwpastore
Copy link
Contributor

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?

@whatthewhat
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants