Problems with alias_method

J

Jan Svitok

Hi Guys,

I'm trying to alias_method in a bit different way. Here's what I'm
trying to do : http://pastie.caboo.se/45668

Any help would be great.

Thanks for your time,
Pratik

Hi,

if I understand correctly, the problem you want to solve is to move
repeat_every before the method definition. You are getting
NoMethorError now, so you've put the line after the method def. This
error is expected, as the repeat_every is called before the
interpreter comes to def...

So, what are you looking for is kind of lazy evaluation. You need to
postpone your code until the method is defined. One way to do this is
to use method_added callback. Just set a flag that you are wainting
for a method definition and then, when the method is defined, do your
stuff. Notice that you get the name of the method as an argument, so
this can be easily extended to handle any method.

module Hello
def self.included(base)
base.extend ClassMethods
end

module ClassMethods
def method_added(method_name)
@waiting ||= false
return unless @waiting
@waiting = false
method = <<-METHOD

define_method:)main_with_schedule) do |*args|
while true
puts "looping"
main_without_schedule(*args)
sleep #{@sleep_time}
end
end
alias_method :main_without_schedule, :main
alias_method :main, :main_with_schedule
METHOD

self.instance_eval(method)
end

def repeat_every(time = 5)
@sleep_time = time
@waiting = true
end
end
end

class Redworld
include Hello

# I want to have repeat_every before main() method. But it gives
method not found error.
repeat_every 2 #formerly commented out

def main
puts "Hello World"
end
# here was: repeat_every 5

end
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top