Problems with alias_method

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

ยทยทยท

On 3/8/07, Pratik <pratiknaik@gmail.com> wrote:

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