无需运算符('.'或'::')直接访问模块方法

Access module method directly without operator ('.' or '::')

我正在尝试构建一个可以包含在任何 class 中并且可以直接调用其方法的模块。

rubygemcolored就是一个很好的例子。例如,我可以在任何地方调用 Colored 模块中的方法,只需执行类似 puts "I am the color blue!".blue 的操作,但那不是任何 class。但我注意到他们调用 String.send(:include, Colored).

如有任何见解,我们将不胜感激。

目标:

module Example
  def do_something
    puts 'foo!'
  end
end

# Instead of calling Example::do_something or Example.do_something,
# I want to do this:
do_something # => 'foo!'

(方法不正确)

module Example
  extend self 

  def do_something
    puts 'foo!'
  end
end

do_something # => undefined local variable or method `do_something' for main:Object (NameError)

(另一种错误方式)

module Example
  extend self # not sure...

  def self.do_something
    puts 'foo!'
  end
end

do_something # => undefined local variable or method `do_something' for main:Object (NameError)

试试运行这样

module Example
  def do_something
    puts 'foo!'
  end
end

include Example
do_something #=> foo!