2012-07-12 76 views
0

我有以下示例包括一個模塊與一類的方法引用該模塊的類被包括

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

回答

1

爲什麼不在模塊定義中包含模塊?

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

0

試試吧

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