Reputation: 18139
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:
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
.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?
Upvotes: 1
Views: 1538
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
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