Cam*_*oth 6 ruby inheritance ruby-on-rails
我希望使用日志设置相对于文件路径的日志记录的默认路径,如下所示:
# /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
Run Code Online (Sandbox Code Playgroud)
理想输出:
# => /path/to/app/models
Run Code Online (Sandbox Code Playgroud)
实际产量:
# => /path/to/lib
Run Code Online (Sandbox Code Playgroud)
因为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"
Run Code Online (Sandbox Code Playgroud)
但是,你可以在self.inherited钩子中解析调用者,如下所示:
# 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"
Run Code Online (Sandbox Code Playgroud)
我不确定解析是多么强大或可移植; 我建议你测试一下.
NB我的Bar继承Foo,与你的问题相反.不要被我们的设置差异搞糊涂.