Molfar
Molfar

Reputation: 1501

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

Upvotes: 1

Views: 1123

Answers (4)

Dorian
Dorian

Reputation: 9185

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

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

Upvotes: 0

Molfar
Molfar

Reputation: 1501

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.

Upvotes: 0

Bijendra
Bijendra

Reputation: 10053

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

Upvotes: 2

Christian Bruckmayer
Christian Bruckmayer

Reputation: 2197

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

Upvotes: 1

Related Questions