Class: Kozeki::Collection::Page

Inherits:
Object
  • Object
show all
Defined in:
lib/kozeki/collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent:, page:) ⇒ Page

Returns a new instance of Page.



71
72
73
74
75
76
# File 'lib/kozeki/collection.rb', line 71

def initialize(parent:, page:)
  @parent = parent
  @page = page

  @total_pages = nil
end

Instance Method Details

#as_jsonObject



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/kozeki/collection.rb', line 93

def as_json
  {
    kind: 'collection',
    name: name,
    items: records.map do |record|
      {
        id: record.id,
        path: ['items', "#{record.id}.json"].join('/'),
        meta: options&.meta_keys ? record.meta.slice(*options.meta_keys) : record.meta,
      }
    end.then do |page|
      options&.max_items ? page[0, options.max_items] : page
    end,
  }.tap do |j|
    j[:page] = page_info if @page
  end
end

#item_pathObject



111
112
113
# File 'lib/kozeki/collection.rb', line 111

def item_path
  @parent.item_path_for_page(@page)
end

#nameObject



78
# File 'lib/kozeki/collection.rb', line 78

def name; @parent.name; end

#optionsObject



79
# File 'lib/kozeki/collection.rb', line 79

def options; @parent.options; end

#page_infoObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/kozeki/collection.rb', line 115

def page_info
  return nil unless @page
  prev_page = 1 < @page ? @parent.item_path_for_page(@page-1) : nil
  next_page = @page < total_pages ? @parent.item_path_for_page(@page+1) : nil
  i = {
    self: @page,
    total_pages:,
    first: @parent.item_path_for_page(1).join('/'),
    last: @parent.item_path_for_page(total_pages).join('/'),
    prev: prev_page&.join('/'),
    next: next_page&.join('/'),
  }
  if @page == 1
    i[:pages] = (1..total_pages).map do |pagenum|
      @parent.item_path_for_page(pagenum).join('/')
    end
  end
  i
end

#recordsObject



82
83
84
85
86
87
88
89
90
91
# File 'lib/kozeki/collection.rb', line 82

def records
  case @page
  when nil
    @parent.records_sorted
  when 0
    raise "[bug] page is 1-origin"
  else
    @parent.records_sorted[(@page - 1) * options.max_items, options.max_items]
  end
end

#total_pagesObject



80
# File 'lib/kozeki/collection.rb', line 80

def total_pages; @parent.total_pages; end