60 lines
1.2 KiB
Ruby
60 lines
1.2 KiB
Ruby
class ApplicationSerializer
|
|
class CollectionSerializer < ApplicationSerializer
|
|
|
|
def initialize(items, serializer, opts = {})
|
|
super(items, opts)
|
|
@collection_name = opts[:collection_name]
|
|
@serializer = serializer
|
|
end
|
|
|
|
def serialize
|
|
list = @item.map { |i| @serializer.for(i).serialize }
|
|
|
|
if @collection_name && item.respond_to?(:total_pages)
|
|
{
|
|
total_count: item.total_count,
|
|
total_pages: item.total_pages,
|
|
current_page: item.current_page,
|
|
page_size: item.limit_value,
|
|
@collection_name.to_sym => list
|
|
}
|
|
else
|
|
list
|
|
end
|
|
end
|
|
end
|
|
|
|
def self.for(data, opts = {})
|
|
if data.respond_to?(:each)
|
|
CollectionSerializer.new(data, self, opts)
|
|
else
|
|
new(data)
|
|
end
|
|
end
|
|
|
|
attr_reader :item
|
|
|
|
def initialize(item, opts = {})
|
|
@item = item
|
|
@options = opts
|
|
end
|
|
|
|
def item_properties(*keys)
|
|
Hash[keys.map { |k| [k.to_sym, @item.send(k.to_sym)] }]
|
|
end
|
|
|
|
def serialize
|
|
@item.as_json
|
|
end
|
|
|
|
def as_json(*args)
|
|
serialize
|
|
end
|
|
|
|
def to_json(*args)
|
|
Rails.cache.fetch(@item.cache_key, version: @item.cache_version) do
|
|
self.as_json(*args).to_json
|
|
end
|
|
end
|
|
end
|