开发者

ruby NameError when including Singleton module in class belonging to another module

When I try to include the Singleton module in a class that itself exists in a module it does not work. Here's an example:

require 'singleton'

module SomeModule
end

class SomeModule::SomeClass
  include Singleton

  def initialize
    @some_variable = 1
  end

  def output
    puts @some_variable
  end
end

SomeClass.instance.output

and the error I get is:

uninitialized constant Object::SomeClass (NameError)

I'm not sure how to tell the Singleton module to look for SomeModule::SomeClass not开发者_StackOverflow中文版 Object::SomeClass


The problem is you are calling the SomeClass class without the prepended module name. Add the module name to get it to work:

SomeModule::SomeClass.instance.output
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜