Class: DropletKit::PaginatedResource

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/droplet_kit/paginated_resource.rb

Constant Summary collapse

PER_PAGE =
20

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(action, resource, *args) ⇒ PaginatedResource

Returns a new instance of PaginatedResource.



10
11
12
13
14
15
16
17
18
# File 'lib/droplet_kit/paginated_resource.rb', line 10

def initialize(action, resource, *args)
  @current_page = 0
  @total = nil
  @action = action
  @resource = resource
  @collection = []
  @args = args
  @options = args.last.kind_of?(Hash) ? args.last : {}
end

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



7
8
9
# File 'lib/droplet_kit/paginated_resource.rb', line 7

def action
  @action
end

#collectionObject (readonly)

Returns the value of attribute collection.



7
8
9
# File 'lib/droplet_kit/paginated_resource.rb', line 7

def collection
  @collection
end

#resourceObject (readonly)

Returns the value of attribute resource.



7
8
9
# File 'lib/droplet_kit/paginated_resource.rb', line 7

def resource
  @resource
end

#totalObject

Returns the value of attribute total.



8
9
10
# File 'lib/droplet_kit/paginated_resource.rb', line 8

def total
  @total
end

Instance Method Details

#==(other) ⇒ Object



57
58
59
# File 'lib/droplet_kit/paginated_resource.rb', line 57

def ==(other)
  each_with_index.each.all? {|object, index| object == other[index] }
end

#[](index) ⇒ Object



24
25
26
# File 'lib/droplet_kit/paginated_resource.rb', line 24

def [](index)
  @collection[index]
end

#each(start = 0, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/droplet_kit/paginated_resource.rb', line 28

def each(start = 0, &block)
  # Start off with the first page if we have no idea of anything yet
  fetch_next_page if total.nil?

  return to_enum(:each, start) unless block_given?
  Array(@collection[start..-1]).each do |element|
    yield(element)
  end

  unless last?
    start = [@collection.size, start].max
    fetch_next_page
    each(start, &block)
  end

  self
end

#last?Boolean

Returns:

  • (Boolean)


46
47
48
49
# File 'lib/droplet_kit/paginated_resource.rb', line 46

def last?
  return true if self.total.nil?
  @current_page == total_pages || self.total.zero?
end

#per_pageObject



20
21
22
# File 'lib/droplet_kit/paginated_resource.rb', line 20

def per_page
  @options[:per_page] || PER_PAGE
end

#total_pagesObject



51
52
53
54
55
# File 'lib/droplet_kit/paginated_resource.rb', line 51

def total_pages
  return nil if self.total.nil?

  (self.total.to_f / per_page.to_f).ceil
end