BigW Consortium Gitlab

group_child_serializer.rb 1.42 KB
Newer Older
1 2 3
class GroupChildSerializer < BaseSerializer
  include WithPagination

4
  attr_reader :hierarchy_root, :should_expand_hierarchy
5

6
  entity GroupChildEntity
7

8
  def expand_hierarchy(hierarchy_root = nil)
9 10 11 12
    @hierarchy_root = hierarchy_root
    @should_expand_hierarchy = true

    self
13 14 15
  end

  def represent(resource, opts = {}, entity_class = nil)
16 17
    if should_expand_hierarchy
      paginator.paginate(resource) if paginated?
18 19 20 21 22 23
      represent_hierarchies(resource, opts)
    else
      super(resource, opts)
    end
  end

24 25
  protected

26
  def represent_hierarchies(children, opts)
27
    if children.is_a?(GroupDescendant)
28
      represent_hierarchy(children.hierarchy(hierarchy_root), opts).first
29
    else
30
      hierarchies = GroupDescendant.build_hierarchy(children, hierarchy_root)
31 32 33
      # 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)
34 35 36 37
    end
  end

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

40 41 42 43 44 45
    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)
46
      hierarchy.flat_map { |child| serializer.represent_hierarchy(child, opts) }
47 48 49
    else
      serializer.represent(hierarchy, opts)
    end
50
  end
51
end