簡體   English   中英

Ruby 獲取當前文件路徑

[英]Get current file path in Ruby

方法如何檢測調用它的當前文件名(未定義)? __FILE__在這種情況下不起作用。

# 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

可以參考ruby中的caller_locations模塊 kernel 返回當前執行棧---一個包含回溯位置對象的數組。

module Foo
  def current_path
    caller_locations.first.label
  end
end

你可以使用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

我已經通過包含的回調完成了

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

然后簡單地使用 class 實例變量。

您可以使用__FILE__獲取當前文件的完整路徑:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM