From: Dave Thomas Date: 2001-02-20T02:02:28+09:00 Subject: [ruby-talk:11119] Re: Auto-magically determine your class/method in Ruby 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