开发者

How to get the full file path of an arbitrary ruby class?

开发者 https://www.devze.com 2022-12-29 10:27 出处:网络
eg: class Base def self.inherited(subclass) puts \"New subclass: #{subclass}\" path_of_subclass = ???? end

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消