Class: Kozeki::Collection

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

Defined Under Namespace

Classes: Page

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, records, options: nil) ⇒ Collection

Returns a new instance of Collection.

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
# File 'lib/kozeki/collection.rb', line 6

def initialize(name, records, options: nil)
  raise ArgumentError, "name cannot include /" if name.include?('/')
  @name = name
  @records = records
  @options = options

  @records_sorted = nil
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



15
16
17
# File 'lib/kozeki/collection.rb', line 15

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/kozeki/collection.rb', line 15

def options
  @options
end

#recordsObject (readonly)

Returns the value of attribute records.



15
16
17
# File 'lib/kozeki/collection.rb', line 15

def records
  @records
end

Instance Method Details

#calculate_total_pages(count) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/kozeki/collection.rb', line 62

def calculate_total_pages(count)
  if options&.paginate && options&.max_items
    count.divmod(options.max_items).then {|(a,b)| a + (b>0 ? 1 : 0) }
  else
    count > 0 ? 1 : 0
  end
end

#item_path_for_page(pagenum) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/kozeki/collection.rb', line 40

def item_path_for_page(pagenum)
  case pagenum
  when 0
    raise "[bug] page is 1-origin"
  when nil, 1
    ['collections', "#{name}.json"]
  else
    ['collections', "#{name}", "page-#{pagenum}.json"]
  end
end

#item_paths_for_missing_pages(item_count_was) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/kozeki/collection.rb', line 51

def item_paths_for_missing_pages(item_count_was)
  total_pages_was = calculate_total_pages(item_count_was)
  if (total_pages_was - total_pages) > 0
    (total_pages+1..total_pages_was).map do |pagenum|
      item_path_for_page(pagenum)
    end
  else
    []
  end
end

#pagesObject



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/kozeki/collection.rb', line 27

def pages
  case
  when records.empty?
    []
  when options&.paginate && options&.max_items
    total_pages.times.map do |i|
      Page.new(parent: self, page: i+1)
    end
  else
    [Page.new(parent: self, page: nil)]
  end
end

#records_sortedObject



17
18
19
20
21
# File 'lib/kozeki/collection.rb', line 17

def records_sorted
  @records_sorted ||= @records.sort_by do |record|
    record.timestamp&.then { -_1.to_i } || 0
  end
end

#total_pagesObject



23
24
25
# File 'lib/kozeki/collection.rb', line 23

def total_pages
  @total_pages ||= calculate_total_pages(records.size)
end