Why can't I use a class instance variable inside a singleton class definition?

泄露秘密 提交于 2019-12-25 16:08:28

问题


I'm trying to set an instance variable inside a singleton class and I can't get it to work.

Here's a simplified version of the problem:

class MyClass
  class << self
    attr :my_attr

    @my_attr = {}

    def my_method (x, y)
      (@my_attr[x] ||= []) << y
    end
  end
end

MyClass.my_method(1, 2)
# => NoMethodError: undefined method `[]' for nil:NilClass

Here's the original code sample:

class Mic
  class Req < Rack::Request; end
  class Res < Rack::Response; end

  class << self
    attr :routes

    @routes = {}

    def call(env)
      dup.call!(env)
    end

    def call!(env)
      (@app||=new).call(env)
    end

    def get(path, opts={}, &blk)
      puts @routes.inspect # nil
      route 'GET', path, opts, &blk
    end

    def route(type, path, opts, &blk)
      (@routes[type]||=[]) << {type: type, path: path, opts: opts, blk: blk}
    end
  end

  def call(env)
    @env = env
    @req = Req.new(env)
    @res = Res.new

    @res.finish
  end
end

回答1:


So, abbreviated code, but what you probably want is to avoid accessing the instance variable as much as possible.

class Mic
  class << self
     def routes
       @routes ||= {}
     end

     def method_which_acccess_routes
       routes[:this] = :that
     end
   end

   def instance_method_access_routes
      Mic.routes[:the_other] = :nope
   end
 end

You can modify routes in place this way without an accessor, but if you need to completely overwrite it, you'll need an attr_writer method for routes as well.



来源:https://stackoverflow.com/questions/23305470/why-cant-i-use-a-class-instance-variable-inside-a-singleton-class-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!