Module: PeijiSan

Defined in:
lib/peiji_san.rb,
lib/peiji_san/view_helper.rb

Overview

Peiji-San uses named scopes to create a thin pagination layer.

class Member < ActiveRecord::Base
  extend PeijiSan
  self.entries_per_page = 32
end

Now you can start scoping your queries by ‘page’:

Member.active.page(2)

Which will return 32 records with an offset of 32, as that’s the second page.

See PeijiSan::PaginationMethods and PeijiSan::ViewHelper for more info.

Defined Under Namespace

Modules: PaginationMethods, ViewHelper

Constant Summary collapse

ENTRIES_PER_PAGE =
32

Instance Method Summary collapse

Instance Method Details

#entries_per_pageObject

Returns the number of entries you want per page.

class Member < ActiveRecord::Base
  extend PeijiSan
  self.entries_per_page = 32
end
Member.entries_per_page #=> 32


84
85
86
# File 'lib/peiji_san.rb', line 84

def entries_per_page
  @entries_per_page
end

#entries_per_page=(entries) ⇒ Object

Sets the number of entries you want per page.

class Member < ActiveRecord::Base
  extend PeijiSan
  self.entries_per_page = 32
end


73
74
75
# File 'lib/peiji_san.rb', line 73

def entries_per_page=(entries)
  @entries_per_page = entries
end

#page(page, entries_per_page = nil) ⇒ Object

Set the current scope to a given page number.

Consider:

class Member < ActiveRecord::Base
  extend PeijiSan
  self.entries_per_page = 32
end

This adds { :limit => 32, :offset => 0 } to the scope:

Member.page(1)

This adds { :limit => 32, :offset => 31 } to the scope:

Member.page(2)

You can optionally override the entries_per_page setting by sepcifying a second argument:

Member.page(2, 5) # Page 2, 5 entries


109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/peiji_san.rb', line 109

def page(page, entries_per_page=nil)
  page = page.blank? ? 1 : page.to_i
  entries_per_page = entries_per_page || self.entries_per_page || ENTRIES_PER_PAGE
  
  entries = limit(entries_per_page).offset((page - 1) * entries_per_page)

  entries.extend(PeijiSan::PaginationMethods)
  entries.current_page = page
  entries.entries_per_page = entries_per_page
  entries.scope_without_pagination = _use_scoped? ? scoped : all

  entries
end