如何使Ruby模块动态化?

时间:2011-05-23 23:13:24

标签: ruby-on-rails ruby

我有四个模型,UserProfileBadgeMembership, 具有几乎相同的previousnext方法。以下示例来自我的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。

2 个答案:

答案 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语言的方法。