Forum: Ruby Problems with alias_method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pratik N. (Guest)
on 2007-03-08 21:39
(Received via mailing list)
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
Jan S. (Guest)
on 2007-03-09 00:24
(Received via mailing list)
On 3/8/07, Pratik <removed_email_address@domain.invalid> 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

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
This topic is locked and can not be replied to.