如何使用自定义方法扩展DataMapper :: Resource [英] How to extend DataMapper::Resource with custom method
问题描述
我有以下代码:
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 = (@current_page || 1) + 2
end
entites
end
end
end
然后我打电话给#paginate:
Then I have call of #paginate:
@photos = Photo.paginate(params[:page])
并得到以下错误:
application error
NoMethodError at /dashboard/photos/
undefined method `paginate' for Photo:Class
在Active记录中,这个概念对我来说很好...我正在使用JRuby通知。我在做什么错?
In Active record this concept works fine for me... I'am using JRuby for notice. What I'am doing wrong?
推荐答案
安德鲁(Andrew),
Andrew,
您可以将DataMapper :: Resource视为实例(行),将DataMapper :: Model视为类(表)。现在,要更改资源或模型级别的默认功能,您可以将包含或扩展添加到模型中。
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.
首先,您需要包装#paginate模块中的方法。我还添加了一个可能无用的#page方法,以显示如何在需要时附加到资源。
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
在您的情况下,您希望#paginate在模型上可用,所以您可以这样做:
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)
希望有帮助!
这篇关于如何使用自定义方法扩展DataMapper :: Resource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!