I have following code:
module DataMapper
module Resource
@@page_size = 25
attr_accessor :current_page
attr_accessor :next_page
attr_accessor :prev_page
def first_page?
@prev_page
end
def last_page?
@next_page
end
def self.paginate(page)
if(page && page.to_i > 0)
@current_page = page.to_i - 1
else
@current_page = 0
end
entites = self.all(:offset => @current_page * @@page_size, :limit => @@page_size + 1)
if @current_page > 0
@prev_page = @current_page
end
if entites.size == @@page_size + 1
entites.pop
@next_page开发者_如何学Go = (@current_page || 1) + 2
end
entites
end
end
end
Then I have call of #paginate:
@photos = Photo.paginate(params[:page])
And getting following error:
application error
NoMethodError at /dashboard/photos/
undefined method `paginate' for Photo:Class
In Active record this concept works fine for me... I'am using JRuby for notice. What I'am doing wrong?
Andrew,
You can think of DataMapper::Resource as the instance (a row) and of DataMapper::Model as the class (a table). Now to alter the default capabilities at either the resource or the model level, you can either append inclusions or extensions to your model.
First you will need to wrap your #paginate method in a module. I've also added a probably useless #page method to show how to append to a resource in case you ever need to.
module Pagination
module ClassMethods
def paginate(page)
# ...
end
end
module InstanceMethods
def page
# ...
end
end
end
In your case, you want #paginate to be available on the model, so you would do:
DataMapper::Model.append_extensions(Pagination::ClassMethods)
If you find yourself in need of adding default capabilities to every resource, do:
DataMapper::Model.append_inclusions(Pagination::InstanceMethods)
Hope that helps!
精彩评论