Skip to content

Instantly share code, notes, and snippets.

@groyoh
Last active December 2, 2015 09:55
Show Gist options
  • Save groyoh/e5763e19919a6d7aaaf1 to your computer and use it in GitHub Desktop.
Save groyoh/e5763e19919a6d7aaaf1 to your computer and use it in GitHub Desktop.
Serializer concept
# 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
@bibstha
Copy link

bibstha commented Dec 2, 2015

@groyoh What does namespace do in the has_one block?

@groyoh
Copy link
Author

groyoh commented Dec 2, 2015

@bibstha the serializer has to look up the serializer for its relationship. The namespace specifies in which module, this lookup should be done. This is really useful when a relationship is polymorphic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment