2017-09-05 05:30:16 -04:00
|
|
|
class GroupChildSerializer < BaseSerializer
|
|
|
|
include WithPagination
|
|
|
|
|
2017-09-15 06:28:21 -04:00
|
|
|
attr_reader :hierarchy_root, :should_expand_hierarchy
|
2017-09-07 13:08:56 -04:00
|
|
|
|
2017-09-05 05:30:16 -04:00
|
|
|
entity GroupChildEntity
|
2017-09-07 13:08:56 -04:00
|
|
|
|
2017-09-12 08:58:44 -04:00
|
|
|
def expand_hierarchy(hierarchy_root = nil)
|
2017-10-10 10:01:42 -04:00
|
|
|
@hierarchy_root = hierarchy_root
|
|
|
|
@should_expand_hierarchy = true
|
|
|
|
|
|
|
|
self
|
2017-09-07 13:08:56 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def represent(resource, opts = {}, entity_class = nil)
|
2017-09-15 06:28:21 -04:00
|
|
|
if should_expand_hierarchy
|
|
|
|
paginator.paginate(resource) if paginated?
|
2017-09-07 13:08:56 -04:00
|
|
|
represent_hierarchies(resource, opts)
|
|
|
|
else
|
|
|
|
super(resource, opts)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-09-08 13:22:33 -04:00
|
|
|
protected
|
|
|
|
|
2017-09-07 13:08:56 -04:00
|
|
|
def represent_hierarchies(children, opts)
|
2017-09-19 07:11:09 -04:00
|
|
|
if children.is_a?(GroupDescendant)
|
2017-09-08 13:22:33 -04:00
|
|
|
represent_hierarchy(children.hierarchy(hierarchy_root), opts).first
|
2017-09-07 13:08:56 -04:00
|
|
|
else
|
2017-09-22 11:36:39 -04:00
|
|
|
hierarchies = GroupDescendant.build_hierarchy(children, hierarchy_root)
|
2017-10-13 09:13:52 -04:00
|
|
|
# When an array was passed, we always want to represent an array.
|
|
|
|
# Even if the hierarchy only contains one element
|
|
|
|
represent_hierarchy(Array.wrap(hierarchies), opts)
|
2017-09-07 13:08:56 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def represent_hierarchy(hierarchy, opts)
|
2017-10-05 05:08:05 -04:00
|
|
|
serializer = self.class.new(params)
|
2017-09-07 13:08:56 -04:00
|
|
|
|
2017-09-15 06:28:21 -04:00
|
|
|
if hierarchy.is_a?(Hash)
|
|
|
|
hierarchy.map do |parent, children|
|
|
|
|
serializer.represent(parent, opts)
|
|
|
|
.merge(children: Array.wrap(serializer.represent_hierarchy(children, opts)))
|
|
|
|
end
|
|
|
|
elsif hierarchy.is_a?(Array)
|
2017-10-10 10:01:42 -04:00
|
|
|
hierarchy.flat_map { |child| serializer.represent_hierarchy(child, opts) }
|
2017-09-15 06:28:21 -04:00
|
|
|
else
|
|
|
|
serializer.represent(hierarchy, opts)
|
|
|
|
end
|
2017-09-07 13:08:56 -04:00
|
|
|
end
|
2017-09-05 05:30:16 -04:00
|
|
|
end
|