向ruby中的现有模块添加类方法

向ruby中的现有模块添加类方法,ruby,module,Ruby,Module,我有一个模块,可以在包含到类中时添加类方法 我想通过编写第一个模块将包含的另一个模块来强制此模块扩展新方法 下面的代码给出了一个示例,说明了我想做的不起作用的事情: 如果能够覆盖第一个模块的“self.included”函数,用我的方法扩展基础,那就太好了 到目前为止,我能够覆盖第一个模块的self.include函数,但调用super不起作用,因此我松开了第一个模块的类方法: module SomeModule def self.included(base) base.send(

我有一个模块,可以在包含到类中时添加类方法

我想通过编写第一个模块将包含的另一个模块来强制此模块扩展新方法

下面的代码给出了一个示例,说明了我想做的不起作用的事情: 如果能够覆盖第一个模块的“self.included”函数,用我的方法扩展基础,那就太好了

到目前为止,我能够覆盖第一个模块的self.include函数,但调用super不起作用,因此我松开了第一个模块的类方法:

module SomeModule

  def self.included(base)
    base.send(:extend, ClassMethods)
  end

  module ClassMethods

    # Some methods

  end

end


module MyNewModule

 def self.included(base)
    base.class_eval do
      def self.included(base)
        base.send(:extend, ClassMethods)
        super(base)
      end
    end
  end

  module ClassMethods

    def my_method
    end

  end

end

SomeModule.send(:include, MyNewModule)

class Pouet

  include SomeModule

  my_method # undefined local variable or method `my_method' for Pouet:Class (NameError)

end

这可能吗?

在包含的块中使用实例求值

在instance_eval块中,您可以访问要包含它的对象,因此您应该能够在其中包含额外的模块

编辑:

必须将字符串传递给instance_eval,因为该块将存储当前上下文


举一个我做过类似工作的例子:

最终我自己成功了

请告诉我这是好的做法还是坏的做法:

module SomeModule

  def self.included(base)
    base.send(:extend, ClassMethods)
  end

  module ClassMethods

    def my_original_method
    end

    # Some methods

  end

end


module MyNewModule

  def self.included(base)
    base.class_eval do

      class << self

        alias_method :old_included, :included

        def included(base)
          old_included(base)
          base.send(:extend, ClassMethods)
        end

      end

    end
  end

  module ClassMethods

    def my_method
    end

  end

end

SomeModule.send(:include, MyNewModule)

class Pouet

  include SomeModule

  my_original_method
  my_method

end
modulesomemodule
def自带(基本)
base.send(:extend,ClassMethods)
结束
模块类方法
定义我的原始方法
结束
#一些方法
结束
结束
模块MyNewModule
def自带(基本)
基本类\u评估do
班