Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

File in which Module or Class is defined

160 views
Skip to first unread message

Trans

unread,
Aug 24, 2005, 7:41:50 AM8/24/05
to
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.

Robert Klemme

unread,
Aug 24, 2005, 8:01:14 AM8/24/05
to

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

Gene Tani

unread,
Aug 24, 2005, 8:55:31 AM8/24/05
to
Well, you could pick thru SCRIPT_LINES__, to find *every* file which
opens a class definition (ok, maybe this isn't that helpful...)

http://redhanded.hobix.com/inspect/whoaScript_lines__.html

rcoder

unread,
Aug 24, 2005, 1:21:50 PM8/24/05
to
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

0 new messages