Class: Hx::Listing::Paginate

Inherits:
Object
  • Object
show all
Includes:
Filter
Defined in:
lib/hx/listing/paginate.rb

Instance Method Summary collapse

Methods included from Filter

#each_entry_path, #get_entry

Methods included from View

#edit_entry

Constructor Details

#initialize(input, options) ⇒ Paginate

Returns a new instance of Paginate.



32
33
34
35
# File 'lib/hx/listing/paginate.rb', line 32

def initialize(input, options)
  @input = Cache.new(input)
  @page_size = options[:page_size]
end

Instance Method Details

#each_entry(selector) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/hx/listing/paginate.rb', line 37

def each_entry(selector)
  @input.each_entry(Path::ALL) do |index_path, index_entry|
    items = index_entry['items'] || []
    if items.empty?
      index_entry = index_entry.dup
      index_entry['pages'] = [index_entry]
      index_entry['page_index'] = 0
      yield index_path, index_entry if selector.accept_path? index_path
    else
      pages = []
      n_pages = (items.size + @page_size - 1) / @page_size
      for num in 0...n_pages
        page_items = items[@page_size * num, @page_size]
        entry = index_entry.dup
        entry['items'] = page_items
        entry['prev_page'] = "#{num}"
        entry['next_page'] = "#{num+2}"
        entry['pages'] = pages
        entry['page_index'] = num
        pages << {'path' => "#{index_path}/#{num+1}", 'entry' => entry}
      end
      pages[0]['path'] = index_path
      pages[0]['entry'].delete('prev_page')
      if pages.size > 1
        index_name = index_path.split('/').last
        pages[0]['entry']['next_page'] = "#{index_name}/2"
        pages[1]['entry']['prev_page'] = "../#{index_name}"
      end
      pages[-1]['entry'].delete('next_page')
      pages.each do |page|
        path = page['path']
        yield path, page['entry'] if selector.accept_path? path
      end
    end
  end
  self
end