Puzzle...cleaner way to redefine a method?

B

Blackie

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
 
A

Alex Young

Blackie said:
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
 
A

Ari Brown

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

Aquarium, for aspect oriented programming
http://aquarium.rubyforge.org/


Aspect Oriented Programming is definitely what your looking for :)



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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top