How to get the full path to an arbitrary ruby ​​class?

eg:

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

Then in another file / class it expands the base.

 class X < Base .... end 

How do I get the path to the rb file of this subclass from the superclass.

+4
source share
2 answers

Use the caller method and parse it for the file name. inherited always called from the file 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 

Run this:

 $ruby b.rb ["b.rb:3"] 
+4
source
 File.expand_path(subclass.to_s) 

Edit: Sorry, I just realized that the original way will not work if they are not defined in one file.

-2
source

Source: https://habr.com/ru/post/1309223/


All Articles