Ruby on rails 在ruby中,如何从超类中的方法访问子类中的当前_文件
我希望为日志设置一个默认路径,相对于使用日志的文件路径,如下所示:Ruby on rails 在ruby中,如何从超类中的方法访问子类中的当前_文件,ruby-on-rails,ruby,inheritance,Ruby On Rails,Ruby,Inheritance,我希望为日志设置一个默认路径,相对于使用日志的文件路径,如下所示: # /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 # foo.rb class Foo d
# /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
# 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"
实际产量:
# => /path/to/app/models
# => /path/to/lib
因为FILE引用的文件是写入它的地方,而不是调用它的地方,所以它返回的是bar.rb文件,但我希望类似这样的东西返回foo.rb文件的路径,即使方法是在bar中定义的
有人有什么建议吗?最简单的建议如下:
# /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
# 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"
#foo.rb
福班
def self.my_文件
@我的档案
结束
结束
#bar.rb
类Bar“/Users/phrogz/Desktop/bar.rb”
但是,您可以在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"
#foo.rb
福班
class“/Users/phrogz/Desktop/bar.rb”
我不确定解析的健壮性和可移植性;我建议你测试一下
注意:我的
Bar
继承自Foo
,与您的问题相反。不要被我们设置中的差异弄糊涂。使用$0而不是调用者。首先[/^[^::::+/]
在Windows上不起作用,因为那里的绝对路径看起来像$DRIVE:$path
(示例C:/Windows/system32
)
取而代之的是
caller.first[/^[^::::+/]
使用caller\u位置。first.absolute\u路径
这当然很有帮助,学习起来也很好,但我想我的问题过于简单了$0返回正在运行的主程序的文件名,该文件名适用于我的示例,但如果我正在运行包含Foo和Bar文件的其他文件(例如,整个Ruby on Rails应用程序),则不会返回该文件名。谢谢你!