包括一个模块与一类的方法引用该模块的类被包括

问题描述:

我有以下示例包括一个模块与一类的方法引用该模块的类被包括

class Test 
    configure_helper 
end 

module ConfigureHelper 
    module ClassMethods 
    def configure_helper 
    end 
    end 
end 

ConfigureHelper有一些更多的功能,其将与在其中包含在模块ClassMethods扩展类。

所以,问题是,如果我使用下面的代码,包括测试类将被加载的模块

Test.send :include, ConfigureHelper 

,并提高对configure_helper一个NoMethodError。

是否有任何方法来附加configure_helper方法,以便不会调用configure_helper?

+0

更新:是不是我创建的类测试,我将只为它提供的功能。所以我不能改变测试类。 我知道我可以通过扩展对象或Test的任何其他父类来达到我想要的效果。但我真的不想这样做,除非它真的有必要。 – cin 2012-07-12 14:41:32

为什么不在模块定义中包含模块?

module ConfigureHelper 
    def self.included base 
    base.extend ClassMethods 
    end 

    module ClassMethods 
    def configure_helper 
    end 
    end 
end 

class Test 
    include ConfigureHelper 

    configure_helper 
end 
+0

我得到'new1.rb:11:'':未定义的局部变量或方法'configure_helper'为Test:Class(NameError)' – 2012-07-12 11:56:36

+0

尝试更新回答 – 2012-07-12 11:57:39

+0

是 - 现在没事了。请检查我的答案。我无法访问Test class中的'configure_helper'。为什么? – 2012-07-12 12:01:58

试试吧

class Test 
    end 

    module ConfigureHelper 
     module ClassMethods 
     def self.included(base) 
     base.class_eval do 
      def configure_helper 
       p 'Yes' 
      end 
     end 
     end 
     end 
    end 


    Test.send(:include, ConfigureHelper::ClassMethods) 

    Test.new.configure_helper 
+0

这里的情况是,那个类Test没有调用configure_helper。我尝试扩展的类已经包含configure_helper。 – cin 2012-07-12 14:40:07