Backport #8662
closed__dir__ not working in eval with binding and filename
Description
It seems that #8436 is not yet fixed, even in 2.0.0-p247. When a filename is passed into eval as the third argument, dir still shows up as nil:
$ cat t.rb
puts "without file => #{eval("__dir__", TOPLEVEL_BINDING).inspect}"
puts "with file => #{eval("__dir__", TOPLEVEL_BINDING, "test/builder/line.ru").inspect}"
$ ruby t.rb
without file => "/usr/local/google/home/srawlins/code/rack__rack"
with file => nil
In the second case, dir should still be the directory name of FILE, not nil. I've attached a file, simple.patch, that is a pretty simple fix.
However, simple.patch makes the eval_string_with_cref() function 5 if-statements deep though (it was previously 4). So I have another patch that is cleaner: cleaner.patch. It adds some refactoring.
Both patch files add a test. Both patch files are written against 2.0.0-p247.
A note: there was a lot of discussion about dir and absolute paths on #3346, and this patch allows dir to return something that is not an absolute path, because it just returns the dirname of the filename passed in. This is what people will expect. Here is ruby 2.0.0-p247:
$ ruby -e 'eval("puts __FILE__", binding, "not-a-file")'
not-a-file
$ ruby -e 'eval("puts File.dirname(__FILE__)", binding, "not-a-file")'
.
$ ruby -e 'eval("puts File.dirname(__FILE__)", binding, "foo/not-a-file")'
foo
Files