Forum: Ruby funky alias problem

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.
polypus (Guest)
on 2006-03-29 03:56
hi,

if i write

module M
  def foo
    old_foo
  end
end

class X
  def foo
    puts X
  end
  def extend_yourself
    alias old_foo foo
    extend M
  end
end

class Y < X
  def foo
    puts Y
  end
end

x = X.new
y = Y.new
x.foo    -> X
y.foo    -> Y
x.extend_yourself
y.extend_yourself
x.foo    -> X
y.foo    -> X !!!

the behaviour i want though is

y.foo    -> Y

what is the best way?

thanks many
polypus (Guest)
on 2006-03-29 04:43
well solving my own problem, i think the simplest way of doing this is
probably

module M
  def foo
    puts M
    @old_foo.call
  end
end


class X
  def foo
    puts X
  end
  def ext
    @old_foo = method :foo
  end
end

class Y < X
  def foo
    puts Y
  end
end

anyway, still keen to hear any second opinions.
unknown (Guest)
on 2006-03-29 06:35
(Received via mailing list)
On Wed, 28 Mar 2006, polypus wrote:

> what is the best way?

harp:~ > cat a.rb

module M
   def foo
     old_foo
   end
   def self.extend_object object
     object.class.module_eval{
       alias old_foo foo
     }
     super
   end
end

class X
   def foo
     puts X
   end
   def extend_yourself
     extend M
   end
end

class Y < X
   def foo
     puts Y
   end
end

x = X.new
y = Y.new
x.foo    #-> X
y.foo    #-> Y
x.extend_yourself
y.extend_yourself
x.foo    #-> X
y.foo    #-> Y


harp:~ > ruby a.rb
X
Y
X
Y


hth.

-a
polypus (Guest)
on 2006-03-29 08:08
thanks that's pretty
This topic is locked and can not be replied to.