Can you produce a complete working example? I'm having trouble
getting it not to not work.... Here's what I'm doing so far:
If you have edge Rails, you can use this diff:
http://dev.rubyonrails.org/attachment/ticket/9128/eval_file_etc.diff
And then run these tests:
railties/test/plugin_load_test.rb
railties/test/initializer_test.rb
In terms of the code in your mail:
a = 1
def x
eval(DATA.read, binding)
end
x # error: a undefined
__END__
puts a
Is that analogous to what's in the original?
I think it is, and I can't get that to run either. But then why do the
tests pass?
I'm doing something very similar:
<macbook of doom:giles> [08-02 10:58] ~
! irb
def eval_var_with_binding(var)
eval(var, binding)
end
=> nil
a = :xyz
=> :xyz
eval_var_with_binding("puts a")
NameError: undefined local variable or method `a' for #<Object:0x349f4>
from (irb):2:in `eval_var_with_binding'
from (irb):2:in `eval_var_with_binding'
from (irb):5
The only thing that's different is the third arg to eval(). e.g.:
eval(IO.read(file), binding, file)
vs.
eval(var, binding)
But it turns out that passing the filename as a third arg only affects
error reporting, according to the Pickaxe.
Here's something else from the Pickaxe:
When using eval, it can be helpful to state explicitly the context in
which the expression should be evaluated, rather than using the
current context. You can obtain a context by calling Kernel#binding
at the desired point.
def get_a_binding
val = 123
binding
end
val = "cat"
the_binding = get_a_binding
eval("val", the_binding) # 123
eval("val") # "cat"
The first eval evaluates val in the context of the binding as it
was as the method get_a_binding was executing. In this binding,
the variable val had a value of 123. The second eval evaluates
val in the toplevel binding, where it has the value "cat".
If the tests are passing but the binding doesn't operate as I expected
it to, I think this may mean that the binding method is entirely
unnecssary at this point, and only passed at all so that you can also
pass the third arg and get the file-specific error-reporting.
···
--
Giles Bowkett
Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org