Friday, May 8, 2009

ruby on rails, ActiveResource::Base, paginate, WillPaginate, RESTful xml resource and paginate

This sample assume that you have a service in the server that respond .xml


class NoteIntranet < ActiveResource::Base
self.site = INTRANET_CREDENTIALS[:site]
self.element_name = 'note'
cattr_reader :per_page
@@per_page = 20
def self.paginate(*args)
options = args.pop
@@per_page = options.delete(:per_page) || @@per_page
WillPaginate::Collection.create((options.delete(:page) || 1), @@per_page) do |pager|
all_elements = self.find(:all, options)
result = all_elements[pager.offset, pager.per_page].to_a
# inject the result array into the paginated collection:
pager.replace(result)
unless pager.total_entries
# the pager didn't manage to guess the total count, do it manually
pager.total_entries = all_elements.size
end
end
end

end


In the controller you may have conditions that are defined in the service, an example is a filter:


@notes = NoteIntranet.paginate(:page => params[:page], :params => { :title => params[:title] })


In the server service, in the controller you have:


@notes = Note.paginate(:page => params[:page], :conditions => ["title like '%?%'",params[:title]] )


This idea came from Gasper - Luis Guardiola

No comments: