开发者

How can you find the name of the file that called a method in Ruby?

开发者 https://www.devze.com 2023-03-28 23:06 出处:网络
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,

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 Strings:

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消