Last active
December 2, 2015 09:55
-
-
Save groyoh/e5763e19919a6d7aaaf1 to your computer and use it in GitHub Desktop.
Serializer concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From this | |
class FooSerializer < ActiveModel::Serializer | |
def id | |
object.uuid | |
end | |
def type | |
object.class.to_s.underscore | |
end | |
attribute :first_name | |
attribute :full_name | |
def full_name | |
first_name + object.last_name | |
end | |
def resource_meta | |
{ | |
something: first_name + object.meta | |
} | |
end | |
has_one :bar, namespace: Api::V2::Serializer, serializer: Api::V2::Serializer, meta: ->(serializer) do | |
{ object.bar_meta } | |
end | |
def bar | |
foobar | |
end | |
def resource_links | |
{ | |
href: "//example.com/link_author/#{object.id}", | |
meta : { | |
stuff: 'value' | |
} | |
} | |
end | |
end | |
# to this | |
class FooSerializer < ActiveModel::Serializer | |
extend ActiveModel::Serializer::Adapter::JsonApi::SerializerMethods | |
id { object.uuid } | |
type { object.class.to_s.underscore } | |
# type "foo" | |
attribute :first_name | |
attribute :full_name do |serializer| | |
serializer.first_name + object.last_name | |
end | |
meta do |serializer| | |
{ | |
something: serializer.first_name + object.meta | |
} | |
end | |
# meta something: "a meta" | |
has_one :bar do | |
namespace Api::V2::Serializer | |
# serializer Api::V2::Serializer | |
meta do |serializer, association_serializer| | |
{ object.bar_meta } | |
end | |
# meta something: :meta | |
link :self do |serializer, association_serializer| | |
href "//example.com/link_author/#{object.id}" | |
meta stuff: 'value' | |
end | |
# link :self, '//example.com/resource' | |
# data { |serializer, association_serializer| serializer.foobar } | |
end | |
link :self do | |
href "//example.com/link_author/#{object.id}" | |
meta stuff: 'value' | |
end | |
# link :self, '//example.com/resource' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bibstha the serializer has to look up the serializer for its relationship. The
namespace
specifies in whichmodule
, this lookup should be done. This is really useful when a relationship is polymorphic.