使用模块

时间:2015-07-21 17:01:25

标签: ruby

我有一个模块,其中包含一些类方法,我想让模块中的类可用。但是,我所做的不起作用。

module Foo
  class << self
    def test
      # this method should be available to subclasses of module Foo
      # this method should be able to reference subclass constants and methods
      p 'test'
    end
  end
end

class Foo::Bar
  extend Foo
end

这失败了:

Foo::Bar.test
NoMethodError: undefined method `test'

我做错了什么?

1 个答案:

答案 0 :(得分:3)

当你contentType: "application/json", dataType: "json", 一个类的模块时,模块的实例方法成为类中的类方法。所以你需要:

extend

如果您还想要一个模块方法module Foo def test puts "hi" end end class Foo::Bar extend Foo end Foo::Bar.test #=> hi ,可以从Foo::test的任何地方调用,请将上述内容更改为:

Foo.test
相关问题