introspection question

J

jdonnell

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 :eek:rigin_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
 
L

Logan Capaldo

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 :eek:rigin_trace
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
 
R

Robert Klemme

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 :eek:rigin_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

Probably because you were not aware of #caller:
http://www.ruby-doc.org/core/classes/Kernel.html#M001968
=> ["(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
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top