我希望设置一个默认的日志记录路径,相对于使用日志的文件路径,如下所示:

# /path/to/lib/bar.rb
class Bar
  def settings_file_path
    File.dirname(File.expand_path(__FILE__))
  end
end

# /path/to/app/models/foo.rb
class Foo < Bar
end

Foo.new.settings_file_path

理想输出:
# => /path/to/app/models

实际输出:
# => /path/to/lib

因为 FILE 引用的是写文件的位置,而不是调用它的位置,所以它返回的是bar.rb文件,但是我想要这样的东西来返回foo.rb文件的路径,即使该方法是在酒吧。

有人有什么建议吗?

最佳答案

最简单的是这样的:

# foo.rb
class Foo
  def self.my_file
    @my_file
  end
end

# bar.rb
class Bar < Foo
  @my_file = __FILE__
end

# main.rb
require_relative 'foo'
require_relative 'bar'
p Bar.my_file
#=> "/Users/phrogz/Desktop/bar.rb"

但是,您可以像下面这样在self.inherited Hook 中解析调用方:
# foo.rb
class Foo
  class << self
    attr_accessor :_file
  end
  def self.inherited( k )
    k._file = caller.first[/^[^:]+/]
  end
end

# bar.rb
class Bar < Foo
end

# main.rb
require_relative 'foo'
require_relative 'bar'

p Bar._file
#=> "/Users/phrogz/Desktop/bar.rb"

我不确定解析的鲁棒性或可移植性。我建议您测试一下。

N.B.我的Bar继承自Foo,即问题的反面。不要被我们设置中的差异所迷惑。

关于ruby-on-rails - 如何从ruby中父类(super class)中的方法访问子类中的当前__FILE__,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4812873/

10-12 12:36
查看更多