Extending the will_paginate Rails Plugin
Recently I needed a little extra functionality for paginating. Specifically, I wanted to know if I was on the last page, and if so, add some content below my list of paginated stuff. Unfortunately, Mislav’s, will_paginate plugin does not provide those methods. All I wanted to be able to (with a collection of @products) do is…
<% if @products.last_page? %> here is the content <% end %>
Adding that method is actually pretty easy. While I’m at it, it makes sense to add a first_page? method also. Will_paginate has the WillPaginate::Collection class that already adds some additional properties to make paginating in views easy. I just needed to add a little more to it. To start, I created a new file named will_paginate_ext.rb in my lib directory. Inside I added…
module WillPaginateExt def first_page? self.current_page == 1 end def last_page? self.current_page == self.total_pages end end class WillPaginate::Collection include WillPaginateExt end
…and inside my environment.rb file, below and outside of the Rails::Initializer block, add the line…
require 'will_paginate_ext'
With those simple additions, I add two new methods to the will_paginate plugin and am now able to figure out if I am on the first or last page of pagination and add content as necessary.
Is there a better way to add functionality to plugins or other objects? Let me know in the comments below.
Your suggestion works very well. Thanks!