扩展模型的实例方法

时间:2011-05-01 16:23:39

标签: ruby-on-rails ruby ruby-on-rails-3

我正在尝试使用railtie在我的应用中扩展特定模型。添加类方法有效,但实例方法也不起作用。我有以下代码:

  class Railtie
    def self.insert
      return unless defined?(::ActiveRecord)
      ::MyApp::MyModel.extend(ModelMethods)
    end
  end

  module ModelMethods
    def hello
      puts "hello"
    end
  end

现在,我可以致电MyModel.hello。但是,如果我想添加一些实例方法,我该怎么办?当我尝试通过::MyApp::MyModel.include(InstanceMethods)添加它时,它会失败,并且会调用私有方法。

1 个答案:

答案 0 :(得分:2)

include是一种私有方法,不能有明确的接收方。您可以使用send

来解决此限制
MyModel.send(:include, InstanceMethods)
相关问题