Class: Payable::ResourceList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/payable/resource_list.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, options = {}) ⇒ ResourceList

Returns a new instance of ResourceList.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/payable/resource_list.rb', line 7

def initialize(type, options = {})
  @type = case type
  when Symbol, String then Payable.const_get(type)
  else type
  end

  @collection   = @type.collection
  @resource_url = Payable.api_url.join(collection)
  @client       = options.delete(:client){ Payable.client }
  @page_num     = options.delete(:page_num){ 1 }
  @page_size    = options.delete(:page_size){ Payable.config.page_size }
  @page_size    = 50 if @page_size < 1
  @page_size    = 250 if @page_size > 250
  @params       = options
  @pages        = {}
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def collection
  @collection
end

#page_sizeObject (readonly)

Returns the value of attribute page_size.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def page_size
  @page_size
end

#pagesObject (readonly)

Returns the value of attribute pages.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def pages
  @pages
end

#paramsObject (readonly)

Returns the value of attribute params.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def params
  @params
end

#resource_urlObject (readonly)

Returns the value of attribute resource_url.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def resource_url
  @resource_url
end

#typeObject (readonly)

Returns the value of attribute type.



5
6
7
# File 'lib/payable/resource_list.rb', line 5

def type
  @type
end

Instance Method Details

#[](index) ⇒ Object



26
27
28
29
30
# File 'lib/payable/resource_list.rb', line 26

def [](index)
  index = (length + index) if index < 0
  page_num, offset = index.divmod(page_size)
  page(page_num + 1)[offset]
end

#eachObject



48
49
50
51
52
53
54
55
# File 'lib/payable/resource_list.rb', line 48

def each
  return to_enum(__callee__) unless block_given?

  0.step.each do |index|
    item = self[index] or break
    yield item
  end
end

#page(num) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/payable/resource_list.rb', line 32

def page(num)
  @pages[num] ||= begin
    response = get(page: num)
    @total_count = response.body[:total_count]
    map response.body[collection.to_sym]
  end
end

#total_countObject Also known as: length



40
41
42
43
44
# File 'lib/payable/resource_list.rb', line 40

def total_count
  @total_count ||= begin
    get(page_size: 1).body[:total_count]
  end
end