Getting the file name in ruby โ€‹โ€‹where the method was called

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

+5
source share
3 answers

You can use Kernel#caller , which returns the current execution stack โ€” an array containing strings of the form file:line or file:line: in 'method' :

 def foo caller[0][/[^:]+/] # OR caller[0].split(':')[0] end 
+5
source

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

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

 def foo caller_locations.first.path end 
+7
source

@Falsetru's answer is correct, but I thought I'd add this bit of code to demonstrate the various results of the proposed methods.

Two files.

hosting.rb

 class Hosting def self.foo puts "__FILE__: #{__FILE__}" puts "__method__: #{__method__}" puts "caller: #{caller}" puts "caller_locations.first.path: #{caller_locations.first.path}" end end 

calling.rb

 require_relative 'hosting' Hosting.foo 

On: ruby calling.rb output:

 __FILE__: /path/to/hosting.rb __method__: foo caller: ["calling.rb:2:in `<main>'"] caller_locations.first.path: calling.rb 
+4
source

Source: https://habr.com/ru/post/1235664/


All Articles