Module: SimplyCouch::Model::PaginationOptions

Included in:
ClassMethods, FindBy, Finders
Defined in:
lib/simply_couch/model/pagination_options.rb

Instance Method Summary collapse

Instance Method Details

#with_pagination_options(options, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/simply_couch/model/pagination_options.rb', line 4

def with_pagination_options(options, &block)
  # Allow for manual setting of total_entries
  # If none given, default fallback will be total_rows
  # This is not true for a paginated find_all_by construction
  total_entries = options.delete(:total_entries)
  # Add limit and skip to options if requested
  if ([:page, :per_page] & options.keys).any? # Pagination active
    page = [options.delete(:page).to_i, 1].max
    per_page = options.delete(:per_page).to_i # Can be string
    per_page = 22 unless per_page > 0 # Nill will be 0
    options[:limit] = per_page
    options[:skip] = (page - 1) * options[:limit]
  elsif options[:offset] && options[:limit] # Sql syntax support
    options[:skip] = options.delete(:offset)
    options.delete(:order)
    page = (options[:skip].to_i / options[:limit].to_i).floor.succ
    per_page = options[:limit]
  else
    page = 1
    per_page = 22
  end
  result = block.call(options)
  if result
    result.instance_eval "      unless respond_to?(:total_rows)\n        def total_rows\n          1\n        end\n      end\n      def total_entries\n        \#{total_entries || 'total_rows'}\n      end\n      alias total_count total_entries\n\n      def \#{current_page_method}\n        \#{page}\n      end\n      def \#{num_pages_method}\n        return 1 if total_entries.zero?\n        (total_entries.to_f / \#{per_page}).ceil\n      end\n      alias :\#{total_pages_method} :\#{num_pages_method}\n      def \#{per_page_method}\n        \#{per_page}\n      end\n    PAGINATION\n  end\n  result\nend\n", __FILE__, __LINE__