I read through posts like this
but was still not satisfied with the solutions given. For example
val = nil
eval "val = 12"
p val
The mention of 'val' twice is a maintenance problem, as you need to
manually update the local variables in code whenever the variables
inside the string change.
val = nil # forgot to update -- manual labor is hard work
eval "first_val = 12 ; second_val = 44" # string has changed
p first_val # oops!
One solution is to change those locals into attributes of the
singleton:
def locals_to_accessors(str)
previous_locals = local_variables
eval str
(local_variables - previous_locals).each { |name|
value = eval name
eval %Q{
class << self
attr_accessor :#{name}
end
}
self.send("#{name}=", value)
}
end
locals_to_accessors %q{
val = 12
foo = "bar"
}
# no errors!
p val
p foo
This seems like a gymnastic workaround. All I want to do insert some
local variables from a config file. Is there really no way to do that?