summaryrefslogtreecommitdiff
path: root/app/serializers/group_child_serializer.rb
blob: 2baef0a57034a689d1f7f57d37e2674372f82bd3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class GroupChildSerializer < BaseSerializer
  include WithPagination

  attr_reader :hierarchy_root, :should_expand_hierarchy

  entity GroupChildEntity

  def expand_hierarchy(hierarchy_root = nil)
    @hierarchy_root = hierarchy_root
    @should_expand_hierarchy = true

    self
  end

  def represent(resource, opts = {}, entity_class = nil)
    if should_expand_hierarchy
      paginator.paginate(resource) if paginated?
      represent_hierarchies(resource, opts)
    else
      super(resource, opts)
    end
  end

  protected

  def represent_hierarchies(children, opts)
    if children.is_a?(GroupDescendant)
      represent_hierarchy(children.hierarchy(hierarchy_root), opts).first
    else
      hierarchies = GroupDescendant.build_hierarchy(children, hierarchy_root)
      # 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)
    end
  end

  def represent_hierarchy(hierarchy, opts)
    serializer = self.class.new(params)

    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)
      hierarchy.flat_map { |child| serializer.represent_hierarchy(child, opts) }
    else
      serializer.represent(hierarchy, opts)
    end
  end
end