From: David Alan Black Date: 2001-03-05T23:42:07+09:00 Subject: [ruby-talk:12019] hooking/wrapping all of a classes methods Hello -- What I mean is: Let's say I write an IO-layer class with a bunch of methods that do something with files. I want every method to lock and unlock the file (or at least check that it is locked, or whatever). I don't feel like having to remember to write that into every method. My current thinking is to automatically wrap the insides of the methods. Here's an example, where my methods are very simple and the code to wrap them just adds a couple of puts's. My question is: how does this rate as a way to do this? Pitfalls? (I sense there might be some in connection with argument handling, though the few tests I've done have been OK.) More concise ways? class Thing def mone puts "hi" end def mtwo(a) puts "bye" end superclass.instance_methods - instance_methods .each do |m| al = "__#{m.id}__" alias_method al, m module_eval <<-EOE def #{m}(*args) puts "Entering method #{m}" #{al}(*args) ensure puts "Leaving method #{m}" end EOE end end # Test t = Thing.new begin t.mone t.mtwo # ArgumentError rescue ArgumentError => msg puts msg Thing.new.mtwo(3) # OK end __END__ => Entering method mone hi Leaving method mone Entering method mtwo Leaving method mtwo wrong # of arguments(0 for 1) Entering method mtwo bye Leaving method mtwo Thanks -- David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav