parsley/app/serializers/application_serializer.rb

62 lines
1.2 KiB
Ruby
Raw Normal View History

2020-08-06 21:23:31 -05:00
class ApplicationSerializer
2020-08-11 11:05:19 -05:00
include Rails.application.routes.url_helpers
2020-08-06 21:23:31 -05:00
class CollectionSerializer < ApplicationSerializer
2020-08-07 12:33:06 -05:00
2020-08-06 21:23:31 -05:00
def initialize(items, serializer, opts = {})
super(items, opts)
2021-11-28 23:19:56 -06:00
@collection_name = 'list'
2020-08-06 21:23:31 -05:00
@serializer = serializer
end
def serialize
list = @item.map { |i| @serializer.for(i).serialize }
if @collection_name && item.respond_to?(:total_pages)
{
2021-11-28 23:19:56 -06:00
totalCount: item.total_count,
totalPages: item.total_pages,
currentPage: item.current_page,
pageSize: item.limit_value,
2020-08-06 21:23:31 -05:00
@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
2020-08-07 12:33:06 -05:00
def item_properties(*keys)
Hash[keys.map { |k| [k.to_sym, @item.send(k.to_sym)] }]
end
2020-08-06 21:23:31 -05:00
def serialize
2020-08-07 12:33:06 -05:00
@item.as_json
2020-08-06 21:23:31 -05:00
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
2020-08-07 12:33:06 -05:00
end