Why can't I use a class instance variable insi

2019-09-02 18:41发布

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条回答
三岁会撩人
2楼-- · 2019-09-02 18:56

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.

查看更多
登录 后发表回答