Created
May 24, 2017 12:46
-
-
Save reggieb/166221a68776f03791d7f1c2f317f0a0 to your computer and use it in GitHub Desktop.
Playing with ActiveModelSerializers to generate a redux friendly data structure.
This file contains hidden or 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
class PickingSerializer < ActiveModel::Serializer | |
attribute :data do | |
{ | |
result: object.id, | |
entities: { | |
orders: { object.id => OrderSerializer.new(object) }, | |
line_items: object.line_items.each_with_object({}) do |line_item, h| | |
h[line_item.id] = LineItemSerializer.new(line_item) | |
end | |
} | |
} | |
end | |
attribute :errors do | |
{ | |
orders: { object.id => object.errors }, | |
line_items: object.line_items.each_with_object({}) do |line_item, h| | |
h[line_item.id] = line_item.errors | |
end | |
} | |
end | |
attribute :meta do | |
{} | |
end | |
class OrderSerializer < ActiveModel::Serializer | |
attributes :id, :uuid, :total_products, :total_price_excl_delivery, :state, | |
:delivery_price_pence, :post_code, :store, :slot, :created_at | |
attribute :line_items do | |
object.line_items.pluck(:id) | |
end | |
end | |
class LineItemSerializer < ::LineItemSerializer | |
attributes :id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment