Class: Alchemy::PageTreeSerializer

Inherits:
BaseSerializer show all
Defined in:
app/serializers/alchemy/page_tree_serializer.rb

Instance Attribute Summary

Attributes inherited from BaseSerializer

#object, #opts

Instance Method Summary collapse

Methods inherited from BaseSerializer

#initialize

Constructor Details

This class inherits a constructor from Alchemy::BaseSerializer

Instance Method Details

#attributesObject



5
6
7
# File 'app/serializers/alchemy/page_tree_serializer.rb', line 5

def attributes
  {"pages" => nil}
end

#pagesObject



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
# File 'app/serializers/alchemy/page_tree_serializer.rb', line 9

def pages
  tree = []
  path = [{id: object.parent_id, children: tree}]
  page_list = object.self_and_descendants.includes(:public_version, {language: :site})
  base_level = object.level - 1
  # Load folded pages in advance
  folded_user_pages = FoldedPage.folded_for_user(opts[:user]).pluck(:page_id)
  folded_depth = Float::INFINITY

  page_list.each_with_index do |page, i|
    has_children = page_list[i + 1] && page_list[i + 1].parent_id == page.id
    folded = has_children && folded_user_pages.include?(page.id)

    if page.depth > folded_depth
      next
    else
      folded_depth = Float::INFINITY
    end

    # If this page is folded, skip all pages that are on a higher level (further down the tree).
    if folded && !opts[:full]
      folded_depth = page.depth
    end

    if page.parent_id != path.last[:id]
      if path.map { |o| o[:id] }.include?(page.parent_id) # Lower level
        path.pop while path.last[:id] != page.parent_id
      else # One level up
        path << path.last[:children].last
      end
    end

    level = path.count + base_level

    path.last[:children] << page_hash(page, level, folded)
  end

  tree
end