我有一个包含一些类方法的模块,我希望模块中的类可以使用这些方法。但是,我正在做的是行不通的。
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'
我做错了什么?
最佳答案
当您从类扩展
模块时,模块的实例方法成为类中的类方法。所以你需要:
module Foo
def test
puts "hi"
end
end
class Foo::Bar
extend Foo
end
Foo::Bar.test #=> hi
如果您还希望有一个模块方法 Foo::test
,它可以在任何地方使用 Foo.test
调用,请将上面的代码更改为:
module Foo
def test
puts "hi"
end
extend self
end
Foo::Bar.test #=> hi
Foo.test #=> "hi"
关于ruby - 使用模块中定义的类方法在同一模块中扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31545266/