Skip to content

Instantly share code, notes, and snippets.

@denmarkin
Created February 8, 2011 21:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@jameydavis
Copy link

Brilliant, just what I needed! Thanks, denmarkin.

@3zcurdia
Copy link

Great Solution, I just made a small modification cause total_pages was missing on my case https://gist.github.com/3100035

  • ruby 1.9.3-p94
  • rails(3.2.6)
  • will_paginate(3.0.3)

@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