How to prepend classmethods

前端 未结 2 1218
轮回少年
轮回少年 2020-12-08 07:59

This question directly relates to this one. But I tried to break it down to the base problem and I didn\'t want to enter even more text into the other question box. So here

相关标签:
2条回答
  • 2020-12-08 08:40

    The problem is that even though you're prepending the module, ClassMethods is still getting extended in. You could do this to get what you want:

    module Extensions
      module ClassMethods
        def bar
          'Extended Bar!'
        end  
      end  
    
      def self.prepended(base)
        class << base
          prepend ClassMethods
        end  
      end  
    end
    

    Note that Extensions itself could be either prepended or included in Foo. The important part is prepending ClassMethods.

    0 讨论(0)
  • 2020-12-08 08:42

    A simpler version:

    module Extensions
      def bar
        'Extended Bar!'
      end  
    end
    
    Foo.singleton_class.prepend Extensions
    
    0 讨论(0)
提交回复
热议问题