ruby - 使用模块中定义的类方法在同一模块中扩展类

标签 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'

我做错了什么?

最佳答案

当您从类扩展模块时,模块的实例方法成为类中的类方法。所以你需要:

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/

相关文章:

ruby-on-rails - Rails - 唯一性导致 "Stack Too Deep"错误

arrays - 组合数组并保留顺序 - 但优先考虑一个数组的顺序而不是另一个

Ruby 文件在最后一个空行之后无法读取内容\n

ruby - 根据新终端选项卡上 .ruby-version 中的值,chruby 没有更改为正确的 ruby​​ 版本

ruby - 使用 'attr_accessor' 定义非标准访问器方法

ruby-on-rails - Neo4j 与 Ruby On Rails

ruby-on-rails - 即使没有通过电子邮件链接确认电子邮件,如何配置设计使用户在注册后登录?

ruby - 安装 libv8 3.11.8.3 时出错

ruby - 如何在不等待 Ruby 响应的情况下发出 HTTP 请求

ruby - "PG::ConnectionBad - could not connect to server: Connection refused"Heroku 上的 Sinatra 服务器