Class: HOALife::Resources::Collection

Inherits:
Object
  • Object
show all
Includes:
Requestable
Defined in:
lib/hoalife/resources/collection.rb

Overview

A collection of resources Usually returned by an index endpoint

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Collection

Returns a new instance of Collection.



10
11
12
13
14
# File 'lib/hoalife/resources/collection.rb', line 10

def initialize(url)
  @url = url
  @meta = {}
  @links = {}
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



8
9
10
# File 'lib/hoalife/resources/collection.rb', line 8

def url
  @url
end

Instance Method Details

#allObject

Return all pages



17
18
19
20
21
22
23
24
25
# File 'lib/hoalife/resources/collection.rb', line 17

def all
  all_resources = resources

  if @meta['current_page'] < @meta['total_pages']
    all_resources += self.class.new(@links['next']).all
  end

  all_resources
end

#current_pageObject



57
58
59
60
61
# File 'lib/hoalife/resources/collection.rb', line 57

def current_page
  data

  @meta['current_page']
end

#firstObject

Just return the first result



28
29
30
31
32
33
34
# File 'lib/hoalife/resources/collection.rb', line 28

def first
  if resources.is_a?(Array)
    resources.first
  else
    resources
  end
end

#lastObject

Just return the last result



37
38
39
# File 'lib/hoalife/resources/collection.rb', line 37

def last
  all.last
end

#order(col, dir = :asc) ⇒ Object



46
47
48
49
# File 'lib/hoalife/resources/collection.rb', line 46

def order(col, dir = :asc)
  safe_dir = dir.to_s.downcase == 'desc' ? 'desc' : 'asc'
  self.class.new add_params_to_url!(order: col, order_dir: safe_dir)
end

#reloadObject



71
72
73
74
75
# File 'lib/hoalife/resources/collection.rb', line 71

def reload
  @data = nil

  self
end

#totalObject Also known as: count, size



63
64
65
66
67
# File 'lib/hoalife/resources/collection.rb', line 63

def total
  data

  @meta['total']
end

#total_pagesObject



51
52
53
54
55
# File 'lib/hoalife/resources/collection.rb', line 51

def total_pages
  data

  @meta['total_pages']
end

#where(params = {}) ⇒ Object

Add query parameters to the URL



42
43
44
# File 'lib/hoalife/resources/collection.rb', line 42

def where(params = {})
  self.class.new add_params_to_url!(params)
end