Paginate arrays with will_paginate

There may come a time when you wish to paginate an ordinary array of objects, as opposed to an ActiveRecord collection. Thankfully will_paginate supports this out of the box, with very little work.

Firstly, you will need to include the will_paginate array library, which comes with will_paginate. To do this either create or add to an existing initializer in config/initializers/. With all projects I tend to create a file named project_library.rb.

config/initializer/project_library.rb

Within this file you need to require the will_paginate array library:

require ‘will_paginate/array’

That’s it, you can now paginate arrays. The following is a simple example:

1
2
3
> arr = (1..100).to_a
> res = arr.paginate :page => 3, :per_page => 10
=> res: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

All usual will_paginate methods are available, such as current_page and total_entries.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>