Module: SparkApi::Paginate

Included in:
Models::Base
Defined in:
lib/spark_api/paginate.rb

Constant Summary collapse

DEFAULT_PAGE_SIZE =
25

Instance Method Summary collapse

Instance Method Details

#collect(result_array) ⇒ Object

Instanciate class instances from array of hash representations.

Needs to be called by all finders that would like to support paging. Takes the hash result set from the request layer and instanciates instances of the class called for the finder.

  • result_array – the results object returned from the api request layer. An array of hashes.

:returns:

An array of class instances for the Class of the calling finder


42
43
44
45
46
47
48
49
50
51
# File 'lib/spark_api/paginate.rb', line 42

def collect(result_array)
  
  # when conducting a count (pagination=count), the result_array is not an array
  # in those cases, simply return the Fixnum
  return result_array unless result_array.kind_of? Array
  
  collection = result_array.collect { |item| new(item)}
  result_array.replace(collection)
  result_array
end

#paginate(*args) ⇒ Object

Replacement hook for will_paginate’s class method

Does a best effort to mimic the will_paginate method of same name. All arguments are passed on to the finder method except the special keys for the options hash listed below.

Special parameters for paginating finders

  • :page – REQUIRED, but defaults to 1 if false or nil

  • :per_page – defaults to CurrentModel.per_page (which is 25 if not overridden)

  • :finder – name of the finder used (default: “get”). This needs to be a class finder method on the class



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/spark_api/paginate.rb', line 19

def paginate(*args)
  options = args.last.is_a?(::Hash) ? args.pop : {}
  page = options.delete(:page) || 1
  items_per_page = options.delete(:per_page) || self.per_page
  finder = (options.delete(:finder) || 'get').to_s
  page_options = {
    "_pagination" => 1,
    "_limit" => items_per_page,
    "_page" => page
  }
  options.merge!(page_options)
  args << options
  collection = send(finder,*args)
end

#per_pageObject

Default per_page limit set on all models. Override this method in the model such ala the will_paginate gem to change



55
56
57
# File 'lib/spark_api/paginate.rb', line 55

def per_page
  DEFAULT_PAGE_SIZE
end