tags:

views:

88

answers:

2

eg:

class Base

    def self.inherited(subclass)
        puts "New subclass: #{subclass}"
        path_of_subclass = ????
    end
end

Then in another file/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.

A: 
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.

Pran
subclass.to_s gives you the name of the class. There isn't necessarily any relationship between the class name and the file name.
Ken Bloom
+1  A: 

Parse caller. 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"]
Ken Bloom
Thanks Ken, I think is just what I need! I did the following to get the file out of the caller array: splits = caller[0].split(":") caller_file = splits[0] + ":" + splits[1] puts 'caller_file=' + caller_fileHmmm, doesn't format very well in these comments.
Travis R