Module: LooseChange::Pagination

Included in:
Base
Defined in:
lib/loose_change/pagination.rb

Instance Method Summary collapse

Instance Method Details

#paginate(opts = {}) ⇒ Object

Short for paginated_by(:all); see #paginated_by for opts.



44
45
46
# File 'lib/loose_change/pagination.rb', line 44

def paginate(opts = {})
  paginated_by(:all, opts)
end

#paginated_by(view_name, opts = {}) ⇒ Object

Returns a will_paginate-compatible set of documents. In opts, :per_page is required, and :page will be set to 1 unless otherwise specified. All other opts will be passed to CouchDB as in :view_by.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/loose_change/pagination.rb', line 24

def paginated_by(view_name, opts = {})
  raise "You must include a per_page parameter" if opts[:per_page].nil?

  opts[:page] ||= 1

  WillPaginate::Collection.create( opts[:page], opts[:per_page] ) do |pager|
    total_result = view("paginated_by_#{ view_name }", :reduce => true)
    pager.total_entries = total_result ? total_result.first : 0

    results = if view_name == :all
                view(view_name, :limit => opts[:per_page], :skip => ((opts[:page].to_i - 1) * opts[:per_page].to_i), :include_docs => true)
              else
                view("by_#{ view_name }", :key => opts[:key],  :limit => opts[:per_page], :skip => ((opts[:page].to_i - 1) * opts[:per_page].to_i), :include_docs => true)
              end
    pager.replace( results )
  end
end

#paginated_view_by(*keys) ⇒ Object

Similar to #view_by, but adds a paginated view compatible with will_paginate.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/loose_change/pagination.rb', line 7

def paginated_view_by(*keys)
  view_name = "paginated_by_#{ keys.join('_and_') }"
  map_code = "function(doc) {
                 if ((doc['model_name'] == '#{ model_name }') && #{ keys.map {|k| existence_check k}.join('&&') }) {
                   emit(#{ key_for(keys) }, 1)
                 }
               }
               "
  reduce_code = "function(keys, values) { return sum(values); }"
  add_view(view_name, map_code, reduce_code)
  view_by(*keys)
end