Introspection question

is there a way for an object to tell you where it was created a la
stacktraces?

I tried to hack it in myself, but it’s really slowwwwwww. Here was my
hack attempt. I also wanted each object to tell me the time it was
created which works fine.

class Object
attr_accessor :mp_created_at
attr_accessor :origin_trace
end

class Class
alias oldNew new
def new(*args, &block)
obj = oldNew(*args, &block)
begin
raise “force a stack trace”
rescue Exception => err
obj.origin_trace = err.backtrace
end
#a hack that I need for a reason which I haven’t taken the time to
figure out
obj.mp_created_at = Time.now() unless obj.frozen?
return obj
end
end

On Sep 5, 2006, at 8:05 PM, jdonnell wrote:

end

Is this close enough?

class Class
alias rb_new new
def new(*args, &block)
stack = caller
obj = rb_new(*args, &block)
obj.origin_trace = stack
obj.mp_created_at = Time.now unless obj.frozen?
obj
end
end

On 06.09.2006 02:00, jdonnell wrote:

end
#a hack that I need for a reason which I haven’t taken the time to
figure out

Probably because you were not aware of #caller:
http://www.ruby-doc.org/core/classes/Kernel.html#M001968

def foo() caller 0 end
=> nil
foo
=> [“(irb):6:in `foo’”, “(irb):7:in `irb_binding’”,
“/usr/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding’”, “:0”]

obj.mp_created_at = Time.now() unless obj.frozen?
return obj

end
end

Kind regards

robert

Thanks :slight_smile: That’s exactly what i was looking for.