Saturn
Saturn

Reputation: 18139

Extending a Ruby parent class' method with a different-named method

I have a class Parent and a class Child (which is a child subclass of Parent).

This is what I want to achieve:

This is what I ended up doing:

class Parent

  def aaaa
    print "A"
  end

end

class Child < Parent

  alias_method :original_aaaa,:aaaa
  def bbbb
    original_aaaa
    print "B"
  end
  alias_method :aaaa,:bbbb

end

c = Child.new
c.aaaa # => AB
c.bbbb # => AB

It works. I guess. But it felt really hackish. Plus, a disadvantage of this is that if I wanted to extend aaaa with the same name either before or after defining bbbb, things get a bit strange.

Is there a simpler way to achieve this?

Upvotes: 1

Views: 1538

Answers (2)

PKul
PKul

Reputation: 1711

Thanks above answer @sawa Below my use case I like to share: super is work by order!

   class Parent
      def aaaa
        print "A"
      end
    end
    
    class Child < Parent
      def aaaa
        super
        print "B"
      end
      alias bbbb :aaaa
    end
    
    Class Grand < Child
      def aaaa
        print "C"
        super
      end
    end
    => :aaa
    
    g = Grand.new
    g.aaaa #=> CAB

Upvotes: 0

sawa
sawa

Reputation: 168081

class Parent
  def aaaa
    print "A"
  end
end

class Child < Parent
  def aaaa
    super
    print "B"
  end
  alias bbbb :aaaa
end

Upvotes: 5

Related Questions