1

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

  • Parent has a method called aaaa.
  • Child has a method called bbbb.

This is what I want to achieve:

  • I want bbbb to be an extension of aaaa. If I call aaaa on a Child object, it will run what aaaa would normally do, plus whatever else in bbbb.
  • Calling bbbb will do the same as above (runs what aaaa would normally do and then do whatever else is in bbbb).

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?

New Alexandria
  • 6,951
  • 4
  • 57
  • 77
Saturn
  • 17,888
  • 49
  • 145
  • 271
  • 3
    The question is... *why*?! – Pete Oct 08 '13 at 02:21
  • I could see reasons for doing this. This question has some thoughts about how to handle this: http://stackoverflow.com/questions/2564391/how-do-i-call-a-super-class-method – timpone Oct 08 '13 at 02:22
  • What do you mean by "child"? Do you mean subclass? – sawa Oct 08 '13 at 02:49
  • You seem to be using the term "extend" in a misleading way. This term is reserved to mean something different than what you probably mean. You should use a different term. – sawa Oct 08 '13 at 02:51
  • @sawa: Thanks. What would you suggest me to use though? – Saturn Oct 08 '13 at 03:03
  • Maybe something like "enhancement", "addition", etc. I am not sure. It is up to you. – sawa Oct 08 '13 at 03:08

2 Answers2

5
class Parent
  def aaaa
    print "A"
  end
end

class Child < Parent
  def aaaa
    super
    print "B"
  end
  alias bbbb :aaaa
end
sawa
  • 165,429
  • 45
  • 277
  • 381
0

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
PKul
  • 1,691
  • 2
  • 21
  • 41