How can I access the current __FILE__ in a subclass from a method in the superclass in ruby
The simplest would be something like this:
# 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"
However, you could parse the caller in a self.inherited hook like so:
# 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"
I'm not certain how robust or portable that parsing is; I suggest you test it.
N.B. My Bar
inherits from Foo
, the reverse of your question. Be not confused by the differences in our setups.