will_paginate sans ActiveRecord object

In one of my projects, I mix together two ActiveRecord objects for listing. There is two ways that I could have done this. A seperate model that enfolds my models or merging them with a concat. I did it this way as it only happened once so no need to create yet-another file.

After reading this post, I got a better idea of what to do. That code was OK but I refactored it into better, cleaner and more understandable code.


def list
foo = Foo.find :all
bar = Bar.find :all
foo_bar = foo.concat bar # merge the two arrays
foo_bar = foo_bar.sort_by { |foos_and_bars| foos_and_bars.created_at } # reorganize by created_at date
end

I then created a private method for pagination. I’ve stuck this in my local controller but the application-wide controller may be a better idea if you use it in different controllers.

Anyway, here be the code:

def paginate_array(array, per_page_param=25, page_number_param=0)
per_page_number = per_page_param.to_i == 0 ? 25 : per_page_param.to_i
page_number = page_number_param.nil? 0 : page_number_param.to_i
page_number = per_page_number * page_number

array_count = 0
array.collect { array_count += 1 } # Array does not have the count method so this works nicely.

WillPaginate::Collection.new(page_number, per_page_number, array_count).concat_array
end

6 Responses to “will_paginate sans ActiveRecord object”


  1. 1 Erin

    Very nice! Thanks!

  2. 2 Zach Inglis

    Thank you, for writing the basis of the code. Saved me a lot of time.

  3. 3 Victoria

    Zach, when did you become such a code Guru?! ;)

  4. 4 Estetik

    Thanks for informations..

  5. 5 Sağlık

    Good.. thanks..

  6. 6 Estetik

    good codes:)

Comments are currently closed.