Issue #8662 has been reported by srawlins (Sam Rawlins).

----------------------------------------
Backport #8662: __dir__ not working in eval with binding and filename
https://bugs.ruby-lang.org/issues/8662

Author: srawlins (Sam Rawlins)
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


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


-- 
http://bugs.ruby-lang.org/