Archive for December, 2007

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 Comments

New Portfolio

Zach Inglis: Portfolio - Version 2. Version 2 is very little as I always relied on company portfolio’s until about a year ago when I started up the portfolio sub-domain.

I’m having one issue with absolutely positioned anchors, but apart from that my portfolio is looking spiffy.

Head on over to see it.

1 Comment