Skip to content

Instantly share code, notes, and snippets.

@denmarkin
Created February 8, 2011 21:48
Show Gist options
  • Save denmarkin/817327 to your computer and use it in GitHub Desktop.
Save denmarkin/817327 to your computer and use it in GitHub Desktop.
How to extend array to support .paginate with will_paginate
# See http://rubydoc.info/gems/will_paginate/2.3.15/WillPaginate/Collection.create
# See https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/array.rb
# Do in application_helper.rb or application_controller.rb (or somewhere else application-wide)
require 'will_paginate/collection'
Array.class_eval do
def paginate(options = {})
raise ArgumentError, "parameter hash expected (got #{options.inspect})" unless Hash === options
WillPaginate::Collection.create(
options[:page] || 1,
options[:per_page] || 30,
options[:total_entries] || self.length
) { |pager|
pager.replace self[pager.offset, pager.per_page].to_a
}
end
end
# Now you can paginate any array, something like
# @posts = NewsPost.search params[:search], :match_mode => :boolean, :field_weights => {:title => 20, :summary => 15}
# filter_by_user
# @posts = @posts.paginate :page => params[:page], :order => 'published_at DESC', :per_page => NewsPost.per_page
@gtd
Copy link

gtd commented Aug 29, 2013

I don't understand the point of this since it's already in the WillPaginate gem as shown in the comment. Just require 'will_paginate/array'. Am I missing something?

@poombavai
Copy link

Hi.. Where should I mention this require 'will_paginate/array' ? In which file? Knidly pls help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment