File in which Module or Class is defined

T

Trans

Is there a built in way to find out what file a class or module is
*initially* defined in? I could do something like:

class AClass
FILE = __FILE__
...
end

But I don't really want to have to hand insert that in every case.

T.
 
R

Robert Klemme

Trans said:
Is there a built in way to find out what file a class or module is
*initially* defined in? I could do something like:

class AClass
FILE = __FILE__
...
end

But I don't really want to have to hand insert that in every case.

I don't know a built in solution but this works for classes:

class Class
def inherited(cl) cl.const_set("FILE", caller[-1].freeze) end
end

Put it at the beginning of the script (or into a file that you require
first). Then you can do

class Foo
end

p Foo::FILE

Of course you can also split the value in file name and line number etc.

Kind regards

robert
 
R

rcoder

Since classes and modules are open, there may be any number of files
which "define" each one. Since SCRIPT_LINES__ is a hash, it's not
ordered according to load sequence, so you won't necessarily be able to
tell which file originally defined the class vs. simply extending it
with some new methods.

Also, you'll need to keep track of which module you're in at any given
time -- you wouldn't want to confuse Foo::Bar with Whiskey::Bar, for
example.

Something along the lines of Robert's example looks more feasible.

-rcoder
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top