gpt4 book ai didi

ruby-on-rails - 如何从 ruby​​ 父类(super class)中的方法访问子类中的当前 __FILE__

转载 作者:数据小太阳 更新时间:2023-10-29 07:07:39 24 4
gpt4 key购买 nike

我希望为日志设置一个默认路径,相对于使用日志的文件路径,像这样:

# /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 文件的路径,即使该方法是在 Bar 中定义的。

有人有什么建议吗?

最佳答案

最简单的是这样的:

# 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"

我不确定解析的健壮性和可移植性;我建议你测试一下。

注意我的 Bar 继承自 Foo,与您的问题相反。不要对我们的设置差异感到困惑。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com