Alex Gutteridge
8/27/2007 5:33:00 AM
On 27 Aug 2007, at 13:45, Aaron Smith wrote:
> Is it possible to override initializations so that anytime an
> object is
> created there is a "filepath" attribute put on it?
>
> maybe?
>
> class Object
> def initialize
> super
> class << self
> attr_accessor :filepath
> end
> self.filepath = $0
> end
> end
>
> See what i'm going for? Any ideas on how to get away with this?
Do you want the name of the file each object is defined in? I think
you want __FILE__ instead of $0 in that case since $0 is always the
top level Ruby program.
Also there is no superclass for Object so super#initialize won't work
I think. This maybe gets closer - but still doesn't actually work:
[alexg@powerbook]/Users/alexg/Desktop(55): cat main.rb
require 'foo'
require 'filepath'
f = Foo.new
p f.filepath
[alexg@powerbook]/Users/alexg/Desktop(56): cat foo.rb
class Foo
end
[alexg@powerbook]/Users/alexg/Desktop(57): cat filepath.rb
class Object
attr_accessor :filepath
end
class Class
alias :old_new :new
def new(*args)
result = old_new(*args)
result.filepath = __FILE__
result
end
end
[alexg@powerbook]/Users/alexg/Desktop(58): ruby main.rb
"./filepath.rb"
We would of course like it to output 'foo.rb' if I understand you right.
Alex Gutteridge
Bioinformatics Center
Kyoto University