Method: WillPaginate::Collection.create

Defined in:
lib/will_paginate/collection.rb

.create(page, per_page, total = nil) {|pager| ... } ⇒ Object

Just like new, but yields the object after instantiation and returns it afterwards. This is very useful for manual pagination:

@entries = WillPaginate::Collection.create(1, 10) do |pager|
  result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
  # inject the result array into the paginated collection:
  pager.replace(result)

  unless pager.total_entries
    # the pager didn't manage to guess the total count, do it manually
    pager.total_entries = Post.count
  end
end

The possibilities with this are endless. For another example, here is how WillPaginate used to define pagination for Array instances:

Array.class_eval do
  def paginate(page = 1, per_page = 15)
    WillPaginate::Collection.create(page, per_page, size) do |pager|
      pager.replace self[pager.offset, pager.per_page].to_a
    end
  end
end

The Array#paginate API has since then changed, but this still serves as a fine example of WillPaginate::Collection usage.

Yields:

  • (pager)


94
95
96
97
98
# File 'lib/will_paginate/collection.rb', line 94

def self.create(page, per_page, total = nil)
  pager = new(page, per_page, total)
  yield pager
  pager
end