简体   繁体   中英

Get current file path in Ruby

How can method detect current file name where it is called (not defined)? __FILE__ is not working in this case.

# lib/foo.rb
module Foo
  def current_path
    # Somehow get path lib/bar.rb
  end
end

# lib/bar.rb
class Bar
  inculde Foo
end

# lib/test.rb
bar = Bar.new
bar.current_path # => Expected lib/bar.rb

You can refer to the caller_locations module from ruby kernel Returns the current execution stack---an array containing backtrace location objects.

module Foo
  def current_path
    caller_locations.first.label
  end
end

You could use caller

# lib/foo.rb
module Foo
  def current_path
    caller[0].split(":")[0]
  end
end

# lib/bar.rb
class Bar
  include Foo
end

# lib/test.rb
bar = Bar.new
bar.current_path # => Expected lib/bar.rb

I've done it through included callback

def included(base)
  base.instance_variable_set :@source_location, caller_locations.first.path
end

And then simply use class instance variable.

You can use __FILE__ to get the full path of the current file:

> __FILE__
=> "/Users/dorianmariefr/src/template-ruby/lib/template-ruby.rb"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM