How to get the full file path of an arbitrary ruby class?
eg:
class Base
def self.inherited(subclass)
puts "New subclass: #{subclass}"
path_of_subclass = ????
end
end
Then in another f开发者_StackOverflowile/class, it extends Base.
class X < Base
....
end
How would I get the path to the rb file of that subclass from the super class.
Use the caller
method and parse it for the filename. inherited
is always called from the file that is defining the class.
Consider the following:
a.rb:
require 'pp'
class Base
def self.inherited(subclass)
pp caller
end
end
b.rb:
require './a.rb'
class Derived < Base
end
Let's run this:
$ruby b.rb
["b.rb:3"]
File.expand_path(subclass.to_s)
Edit: Sorry, I just realized the original way would not work if they aren't defined in the same file.
精彩评论