Module: ActiveResource::Pagination::ClassMethods

Defined in:
lib/active_resource_pagination.rb

Instance Method Summary collapse

Instance Method Details

#count(options) ⇒ Object

returns the total_entries count for the paginated result.

method expects the returned xml to be in the format of:

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <count type="integer">5</count>
</hash>


34
35
36
# File 'lib/active_resource_pagination.rb', line 34

def count(options)
  find(:one, :from => :count, :params => options).count.to_i
end

#paginate(options = {}) ⇒ Object

use same method signatures as find(), optional additional parameters:

page - current page
per_pape - entries per page
total_entries - total entries count

if resource backend doesn’t paginate and retursn all result, then this method automatically sets the total_entry count from the result. Otherwise, you have to pass in the :total_entries count value manually.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/active_resource_pagination.rb', line 46

def paginate(options={})
  pg_options, find_options = options.partition{|k,v| [:page, :per_page, :total_entries].include?(k)}
  
  pg_options[:page] ||= 1
  pg_options[:per_page] ||= per_page
  
  WillPaginate::Collection.create(pg_options[:page], pg_options[:per_page], pg_options[:total_entries]) do |pager|
    find_options[:params] = (find_options[:params] || {}).merge(:offset => pager.offset, :limit => pager.per_page)  
    
    arr = find(:all, find_options) || []
    if pg_options[:total_entries]
      pager.total_entries = pg_options[:total_entries]
    else 
      pager.total_entries = arr.size > pager.per_page ? arr.size : count(find_options[:params])
    end
    
    if arr.size > per_page
      pager.replace arr[pager.offset, pager.per_page]
    else
      pager.replace arr
    end
  end
end