2016-10-28 08:32:07 -04:00
|
|
|
class EnvironmentSerializer < BaseSerializer
|
2017-09-04 12:04:33 -04:00
|
|
|
include WithPagination
|
|
|
|
|
2017-02-07 07:11:15 -05:00
|
|
|
Item = Struct.new(:name, :size, :latest)
|
2017-02-02 07:10:31 -05:00
|
|
|
|
2016-10-28 08:32:07 -04:00
|
|
|
entity EnvironmentEntity
|
2017-02-02 07:10:31 -05:00
|
|
|
|
2017-02-03 06:03:57 -05:00
|
|
|
def within_folders
|
2017-02-02 07:10:31 -05:00
|
|
|
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-08-21 11:46:45 -04:00
|
|
|
items = resource.order('folder ASC')
|
2017-02-10 03:36:52 -05:00
|
|
|
.group('COALESCE(environment_type, name)')
|
2017-08-21 11:46:45 -04:00
|
|
|
.select('COALESCE(environment_type, name) AS folder',
|
2017-02-10 03:36:52 -05:00
|
|
|
'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?
|
2017-02-02 07:10:31 -05:00
|
|
|
|
2017-02-10 03:36:52 -05:00
|
|
|
environments = resource.where(id: items.map(&:last_id)).index_by(&:id)
|
2017-02-02 07:10:31 -05:00
|
|
|
|
2017-02-10 03:36:52 -05:00
|
|
|
items.map do |item|
|
2017-08-21 11:46:45 -04:00
|
|
|
Item.new(item.folder, item.size, environments[item.last_id])
|
2017-02-02 07:10:31 -05:00
|
|
|
end
|
|
|
|
end
|
2016-10-28 08:32:07 -04:00
|
|
|
end
|