Class: JSONdb::PaginatedHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/jsondb/paginated_hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePaginatedHash

Returns a new instance of PaginatedHash.



7
8
9
10
# File 'lib/jsondb/paginated_hash.rb', line 7

def initialize
  super
  @per_page = 20
end

Instance Attribute Details

#per_pageObject

Returns the value of attribute per_page.



5
6
7
# File 'lib/jsondb/paginated_hash.rb', line 5

def per_page
  @per_page
end

Instance Method Details

#page(page_number) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/jsondb/paginated_hash.rb', line 12

def page(page_number)
  first_item = @per_page * (page_number - 1)
  last_item = first_item + (@per_page - 1)
  keys_to_include = keys[first_item..last_item]
  new_hash = self.select { |k, v| keys_to_include.include?(k) }
  return new_hash
end

#total_pagesObject



20
21
22
23
24
25
26
27
# File 'lib/jsondb/paginated_hash.rb', line 20

def total_pages
  # pages = all keys divided by per_page, giving a integer result without mod
  pages = self.keys.count / @per_page
  # pages = pages + 1 if there are some modulo after that calculation
  # so 0 / 20 = 0 + 0 ; 1 /20 = 0 + 1 ; 60 / 20 = 3 + 0 ; 65 / 20 = 3 + 1 
  pages = pages + 1 if self.keys.count % @per_page > 0
  return pages
end