如何在Ruby中包装实例和类方法?

Mis*_*hko 1 ruby

我想在类中添加D一些由实例方法和类方法组成的常用功能.我尝试像下面这样做,但它没有用.实现这一目标的正确方法是什么?

module A
  def foo
    puts "foo!"
  end
end

module B
  def wow
    puts "wow!"
  end
end

module C
  include A   # instance methods
  extend B    # class methods
end

class D
  include C
end

D.new.foo
D.wow
Run Code Online (Sandbox Code Playgroud)

Mau*_*res 6

你必须像这样定义C才能做你想做的事:

module C
  include A

  def self.included( base )
    base.extend B #"base" here is "D"
  end

end
Run Code Online (Sandbox Code Playgroud)