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