From: Bryan Zarnett Date: 2001-02-20T02:10:09+09:00 Subject: [ruby-talk:11121] Re: Auto-magically determine your class/method in Ruby Thats great. I would write a long reply but I gotta play with that and change some code. Thanxs. Cool. Bryan --- Dave Thomas wrote: > Bryan Zarnett writes: > > > Is their a way to auto-magically determine the > class > > and method that called an operation in another > class. > > For example, I have a logger class that would like > to > > embed in the output line the Class and operation > that > > logged a message. I don't want to have to pass > this > > information as an argument if I have to. > > This is Ruby. Of _course_ there is... :) > > Here's the logging stuff. I made a global function > called log, and > encapsulated the actual logging within a class > Logger. The global > function picks up the value of 'self', and passes > it, along with the > args, to the real logger function. There, we get the > name of self's > class, and use the caller function to get the file > name, line number > and method name of the invocation of 'log'. > > def log(*args) > Logger.log(self, *args) > end > > class Logger > def Logger.log(fromObject, *args) > fromClass = fromObject.class.to_s > fileEtc = caller(2)[0] > txt = args.shift > printf "Class > #{fromClass}[#{fromObject.id}] (#{fileEtc}): > #{txt}\n", *args > end > end > > # Let's test this > > class Dave > def doSomething > log("Fortran code is %s", "A") > end > end > > log("Toplevel") > > Dave.new.doSomething > > #=> > Class Object[537712200] (t.rb:23): Toplevel > Class Dave[537684200] (t.rb:19:in > `doSomething'): Fortran code is A > > > > Regards > > > Dave > > > _______________________________________________________ Do You Yahoo!? Get your free @yahoo.ca address at http://mail.yahoo.ca