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
So, abbreviated code, but what you probably want is to avoid accessing the instance variable as much as possible.
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 forroutes
as well.