I am attempting to add a method to all objects which allows adding variables to instances on the fly. However, I have run into the issue that when I begin the class block, the method arguments are out of scope and thus no longer available.
How might I access the method arguments from within the class block? Or is there a better way to do this?
class Object
def addvar(name, value = nil)
puts name # => "test"
class << self
puts name # => returns nil!
attr_accessor name # => nil is not a symbol nor a string (TypeError)
end
self.instance_variable_set("@" + name.to_s, value)
end
end
x = Object.new
x.addvar("test", 3)
It's also possible to use eval with string substitution, but that's something I would rather avoid for security reasons:
class Object
def addvar(name, value = nil)
eval("class << self
attr_accessor :#{name}
end
self.#{name} = #{value}")
end
end
x = Object.new
x.addvar(:test, 3)
puts x.test