From: Alex Young Date: 2007-10-20T04:19:03+09:00 Subject: Re: Puzzle...cleaner way to redefine a method? Blackie wrote: > Here's a puzzle. There must be a cleaner way to do this. > > I would like to have users of this class be able to call "set_wrapper" > and define pre and post behavior on the "working" method. The only > simple way I've found is evaling a string the redefines "working". > Searching threads on instance and class_eval tends to turn up an oil > slick of arguments and misinformation. Help is apprecaited! > > ~~~~~~~~~~ > class Thing > def set_wrapper(string) > eval(string) > end > > def working > yield > end > > def main > working do > p 'test' > end > end > end > > a = Thing.new > > a.main > > a.set_wrapper("def working; p 'pre'; yield; p 'post'; end") > > a.main Try this (untested): class Thing def add_pre_call(&prc) (@pre_procs ||= []) << prc end def add_post_call(&prc) (@post_procs ||= []) << prc end def working @pre_procs.each {|p| p.call} if @pre_procs yield @post_procs.each{|p| p.call} if @post_procs end end a = Thing.new a.main a.add_pre_call { p 'pre' } a.add_post_call { p 'post' } a.main -- Alex