Is there a nice, recommended way to get the name of the file that called a method? I don't want to pass __FILE__
every time. The closest thing I've found is taking the first element of Kernel.caller
, which is okay but has the calling line number appended like "test.rb:7"
. It's easy enough to strip off, but using it see开发者_开发技巧ms like something that might be dependent on the interpreter or might change in the future.
In Ruby 2.0+ you can do this using Kernel#caller_locations
. It's very similar to caller
, with the added benefit that you don't need to parse out the file name manually, since it returns Thread::Backtrace::Location
objects instead of String
s:
file1.rb
:
def some_method
puts caller_locations.first.path
end
file2.rb
:
require_relative './file1'
some_method
Shell:
$ ruby file2.rb
file2.rb
Perhaps it's safer than you think? I found this other post http://snippets.dzone.com/posts/show/2787 where someone did something similar to what you're suggesting...
精彩评论