2017-08-17 22:00:37 +05:30
|
|
|
class EnvironmentSerializer < BaseSerializer
|
2018-03-17 18:26:18 +05:30
|
|
|
include WithPagination
|
|
|
|
|
2017-08-17 22:00:37 +05:30
|
|
|
Item = Struct.new(:name, :size, :latest)
|
|
|
|
|
|
|
|
entity EnvironmentEntity
|
|
|
|
|
|
|
|
def within_folders
|
|
|
|
tap { @itemize = true }
|
|
|
|
end
|
|
|
|
|
|
|
|
def itemized?
|
|
|
|
@itemize
|
|
|
|
end
|
|
|
|
|
|
|
|
def represent(resource, opts = {})
|
|
|
|
if itemized?
|
|
|
|
itemize(resource).map do |item|
|
|
|
|
{ name: item.name,
|
|
|
|
size: item.size,
|
|
|
|
latest: super(item.latest, opts) }
|
|
|
|
end
|
|
|
|
else
|
|
|
|
super(resource, opts)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def itemize(resource)
|
2017-09-10 17:25:29 +05:30
|
|
|
items = resource.order('folder ASC')
|
2017-08-17 22:00:37 +05:30
|
|
|
.group('COALESCE(environment_type, name)')
|
2017-09-10 17:25:29 +05:30
|
|
|
.select('COALESCE(environment_type, name) AS folder',
|
2017-08-17 22:00:37 +05:30
|
|
|
'COUNT(*) AS size', 'MAX(id) AS last_id')
|
|
|
|
|
|
|
|
# It makes a difference when you call `paginate` method, because
|
|
|
|
# although `page` is effective at the end, it calls counting methods
|
|
|
|
# immediately.
|
|
|
|
items = @paginator.paginate(items) if paginated?
|
|
|
|
|
|
|
|
environments = resource.where(id: items.map(&:last_id)).index_by(&:id)
|
|
|
|
|
|
|
|
items.map do |item|
|
2017-09-10 17:25:29 +05:30
|
|
|
Item.new(item.folder, item.size, environments[item.last_id])
|
2017-08-17 22:00:37 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|