Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file name in ruby where method was called

Tags:

ruby

I have a method foo and it is called in a script script001.rb how should I write the foo method so that it returns the file name of a script that called it?

like image 981
Nodir Nasirov Avatar asked Nov 11 '15 05:11

Nodir Nasirov


1 Answers

To avoid needing to deal with caller style strings, you can use Kernel#caller_locations, instead. It returns you an array of Thread::Backtrace::Location objects, which has some convenient methods available for you.

To get the filename, in your case, you can use the #path method:

def foo
  caller_locations.first.path
end
like image 102
Drenmi Avatar answered Oct 27 '22 18:10

Drenmi