Module: ShopifyAPI::Kaminari

Defined in:
lib/shopify-kaminari.rb

Overview

add Kaminari pagination support to ShopifyAPI

Constant Summary collapse

@@per =
25

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.perInteger

get limit of rows per page

Examples:

Get the current per per page

current_per = ShopifyAPI::Kaminari.per

Returns:

  • (Integer)

    the per



15
16
17
# File 'lib/shopify-kaminari.rb', line 15

def per
  @@per
end

.per=(value) ⇒ Integer

set limit of rows to return per page

Examples:

Set limit per page to 50

ShopifyAPI::Kaminari.per = 50

Parameters:

  • value (Integer)

    The new limit per row value

Returns:

  • (Integer)

    the limit per row



25
26
27
# File 'lib/shopify-kaminari.rb', line 25

def per=(value)
  @@per = value
end

Instance Method Details

#paginate(options = {}) ⇒ Array

paginates a ShopifyAPI::Base resource

Examples:

Paginate all ShopifyAPI::Product

@products = ShopifyAPI::Product.page :page => params[:page]

Paginate per 15

@products = ShopifyAPI::Product.page :page => params[:page], :per => 15

Parameters:

  • options (Hash, Integer) (defaults to: {})

    Can be either a Hash like this: => Integer, :per => Integer, or the page number

Returns:

  • (Array)

    Array of ShopifyAPI resources



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/shopify-kaminari.rb', line 38

def paginate(options = {})
  options = {:page => options} if options.class == Fixnum
  options = {} if options.nil?
  
  # create params for pagination
  params = {
    :page   => options[:page] || 1,
    :limit  => options[:per]  || 25
  }
  
  # remove pagination params from options
  options.delete :page
  options.delete :per
  
  # merge any params from options
  params = params.merge options[:params] if options.include? :params
  
  # remove params from options
  options.delete :params
  
  # create arguments to pass to ActiveResource find
  args = {:params => params}.merge options
  
  # run the query
  result = self.find :all, args
  
  # add instance methods to result Array to support paginating with Kaminari
  result.instance_eval <<-EVAL
    def current_page; #{args[:params][:page]}; end
    def total_pages; #{self.count / args[:params][:limit] + 1}; end
    def limit_value; #{args[:params][:limit]}; end
  EVAL
  
  result
end