Extending a Ruby module in another module, including the module methods

后端 未结 5 818
北海茫月
北海茫月 2020-12-02 23:12

Whenever I try to extend a ruby module, I lose the module methods. Neither include nor extend will do this. Consider the snippet:

module A 
  def self.say_         


        
5条回答
  •  -上瘾入骨i
    2020-12-02 23:19

    I don't think there's any simple way to do it.

    So here is a complex way:

    module B
      class << self
        A.singleton_methods.each do |m|
          define_method m, A.method(m).to_proc
        end
      end
    end
    

    You can put it in a helper method like this:

    class Module
      def include_module_methods(mod)
        mod.singleton_methods.each do |m|
          (class << self; self; end).send :define_method, m, mod.method(m).to_proc
        end
      end
    end
    
    module B
      include_module_methods A
    end
    

提交回复
热议问题