ruby - 在另一个模块内扩展模块

时间:2021-05-10 23:20:51

I'm trying to define a couple of modules to easily add in some instance and class methods to other classes, here's what I'm doing:

我正在尝试定义几个模块,以便轻松地将一些实例和类方法添加到其他类中,这就是我正在做的事情:

module Foo
  module Bar
    def speak
      puts "hey there"
    end
  end
  module Baz
    extend Foo::Bar

    def welcome
      puts "welcome, this is an instance method"
    end
  end
end

class Talker
  include Foo::Baz
end

Talker.new.welcome
Talker.speak

The output of this is:

这个输出是:

welcome, this is an instance method
undefined method 'speak' for Talker.class (NoMethodError)

I was expecting Talker to have the 'speak' method since it includes Foo::Baz which itself extends Foo::Bar.

我期待Talker拥有'speak'方法,因为它包括Foo :: Baz,它本身扩展了Foo :: Bar。

What am I missing?

我错过了什么?

2 个解决方案

#1


20  

You can try this:

你可以试试这个:

module Baz
  extend Foo::Bar

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

  def welcome
    puts "welcome, this is an instance method"
  end
end

This will auto-extend all classes in wich Baz is included.

这将自动扩展包含Baz的所有类。

PS:

PS:

extend Foo::Bar in module Baz was in original snippet, this code do not influence on method def self.included(base).

在模块Baz中扩展Foo :: Bar是原始片段,此代码不影响方法def self.included(base)。

#2


4  

try this:

尝试这个:

class Talker
   extend Foo::Baz
end

since you want to call Talker.speak as a class method and not as an instance method (like Talker.new.speak) you have to include the Foo:Baz in a way that the class will take the methods itself.

因为你想把Talker.speak作为一个类方法而不是像实例方法一样(比如Talker.new.speak),你必须包含Foo:Baz,这个类将采用方法本身。

One possibility is to use 'extend' (as above) the other is modifying it's eigenclass:

一种可能性是使用'extend'(如上所述),另一种可能是修改它的本征类:

class Talker
  class << self
    include Foo::Baz
  end
end

#1


20  

You can try this:

你可以试试这个:

module Baz
  extend Foo::Bar

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

  def welcome
    puts "welcome, this is an instance method"
  end
end

This will auto-extend all classes in wich Baz is included.

这将自动扩展包含Baz的所有类。

PS:

PS:

extend Foo::Bar in module Baz was in original snippet, this code do not influence on method def self.included(base).

在模块Baz中扩展Foo :: Bar是原始片段,此代码不影响方法def self.included(base)。

#2


4  

try this:

尝试这个:

class Talker
   extend Foo::Baz
end

since you want to call Talker.speak as a class method and not as an instance method (like Talker.new.speak) you have to include the Foo:Baz in a way that the class will take the methods itself.

因为你想把Talker.speak作为一个类方法而不是像实例方法一样(比如Talker.new.speak),你必须包含Foo:Baz,这个类将采用方法本身。

One possibility is to use 'extend' (as above) the other is modifying it's eigenclass:

一种可能性是使用'extend'(如上所述),另一种可能是修改它的本征类:

class Talker
  class << self
    include Foo::Baz
  end
end