From: Jakub Travnik Date: 2001-11-25T00:38:11+09:00 Subject: [ruby-talk:26340] Re: dynamically redefining methods try this: module Loggable def self.append_features(klass) klass.instance_methods.each do |method| klass.class_eval " alias ___#{method} #{method};"+ " def #{method}(*params,&block);"+ " ___#{method}(*params,&block);"+ " puts 'call to #{method} logged';"+ " end;" end end end class Test def foo puts "hello world" end def bar puts "hello universe" end include Loggable end Jakub Travnik jabber://jtra@jabber.com ICQ: 66770334 (deprecated) Massimiliano Mirra wrote: > I would like to include logging capabilities to a class by just > including a module. This is what I have tried: > > > module Loggable > def self.append_features(klass) > klass.instance_methods.each do |method| > eval "class #{klass}" > eval " def #{method}" > eval " super" > eval " puts 'call to #{method} logged'" > eval " end" > eval "end" > end > end > end > > class Test > def foo > puts "hello world" > end > def bar > puts "hello universe" > end > include Loggable > end > > Apparently, the eval'ed code in Loggable does not work because of its > context, i.e. a class definition does not begin to a method inside a > module. Can this be worked around? Or are there better ways to > accomplish this? > > Massimiliano > >