RCR 309: __DIR__
Submitted by transami (Sat Jul 30 21:54:29 UTC 2005)
Very simple. We have __FILE__, I sometimes need File.dirname(__FILE__). It would be nice if __DIR__ were equal to that. I have tried to use __DIR__ = File.dirname(__FILE__). But Ruby won't recognize it as a constant. Even so it would be nice if it were built in.
At the very least:
irb(main):001:0> __DIR__ = File.dirname(__FILE__)
irb(main):002:0> def x
irb(main):003:1> p __DIR__
NameError: undefined local variable or method `__DIR__' for main:Object
from (irb):3:in `x'
But again built-in would be even better.
Add __DIR__ as a built in constant.
__DIR__ is useful info and the enduser can't get a similar constant to __FILE__ (w/o a hack at least).
__DIR__ = File.dirname(__FILE__)
You could define it as a method:
Ah, Kernel method. Of course. Thanks. Had constant stuck in my mind for some reason.
I should point out for those who don;t see it right off, that this is still a viable addition despite it being definable as a kernel method. Notice that the kernel method will always return the directory location of the file it is defined in, not the one you call it from. So it doesn't really work.
(/^(.+)?:\d+/ =~ caller) ? File.dirname($1) : nil
Hey, thanks! That went right into Facets. If you would like I can credit you in the source code, whomever you are?
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .