[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Puzzle...cleaner way to redefine a method?

Blackie

10/19/2007 7:05:00 PM

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

2 Answers

Alex Young

10/19/2007 7:19:00 PM

0

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

Ari Brown

10/19/2007 9:59:00 PM

0

I have to go to dinner now, but here's something quick you should
look at:

Aquarium, for aspect oriented programming
http://aquarium.ruby...


Aspect Oriented Programming is definitely what your looking for :-)



--------------------------------------------|
If you're not living on the edge,
then you're just wasting space.