From: Patrick Hurley Date: 2006-09-08T00:43:02+09:00 Subject: Re: Has a method been called? On 9/7/06, Jan Svitok wrote: > On 9/7/06, aidy wrote: > > Hi, > > Is it possible to find out if a method has been called except by adding > > a flag to it? > > > > class Whatever > > @flag = 0 > > > > def method_called > > @flag += 1 > > end > > > > def has_method_been_called > > false > > return true if @flag > 0 > > end > > > > end > > > > Cheers > > > > Aidy > > If it's enough for you to know that off-line, you can use rcov or > ruby-prof for that. Run rcov and see whether it's code was visited. If > you need to know in the runtime, that's another story ;-) > > You can also whip up a little meta programming mess (warning thrown together, collision causing, not thread safe code follows): class Module def flag_use(sym) self.instance_eval do define_method "#{sym}_called?" do false end flag_name = "use_flagged_#{sym}".to_sym alias_method flag_name, sym define_method sym do self.class.instance_eval do alias_method sym, flag_name define_method "#{sym}_called?" do true end end flag_name end end end end Then... class Foo def bar puts :bar end flag_use :bar end f = Foo.new p f.bar_called? f.bar p f.bar_called? pth