我有四个模型,User
,Profile
,Badge
和Membership
,
具有几乎相同的previous
和next
方法。以下示例来自我的User
模型。
def next
self.class.find :first,
:conditions => [ "created_at > ? AND user_id = ?",
self.created_at, self.user_id ],
:order => "created_at ASC"
end
def previous
self.class.find :first,
:conditions => [ "created_at < ? AND user_id = ?",
self.created_at, self.user_id ],
:order => "created_at DESC"
end
我没有为每个模型重复四次基本相同的方法,而是尝试将这些方法放入外部模块Extensions::Utility
中,以便每个模型都可以include Extensions::Utility
。
实现此方法的最佳方法是什么,以便它支持user
动态替换其他模型?
我的环境是Ruby / Rails 3.0.6。
答案 0 :(得分:2)
Tilo的回答有一点。我将方法next
更改为nekst
。
module Extensions
module Utility
def id; "#{self.class.downcase}_id" end
def nekst
self.class.find :first,
:conditions => [ "created_at > ? AND #{id} = ?",
self.created_at, self.send(id) ],
:order => "created_at ASC"
end
def previous
self.class.find :first,
:conditions => [ "created_at < ? AND #{id} = ?",
self.created_at, self.send(id) ],
:order => "created_at DESC"
end
end
end
答案 1 :(得分:2)
请注意“next”是Ruby语言中的关键字!!
我建议不要定义任何名称属于Ruby语言的方法。