P
Philippe Lang
Hi Ruby gurus,
Let's say we have a Parent class, and a Child1 class that inherits from
the Parent class.
I'd like to create a Child2 class that inherits most of the Child1
class, except for one method, which I'd like to override completely. The
problem is that I need to call the method in the Parent class, and
apparently "super.super" is not supported:
----------------------------
class Parent
def go
puts 'parent'
end
end
class Child1 < Parent
def go
super
puts 'child1'
end
def a_method_id_like_to_inherit
end
end
class Child2 < Child1
def go
super.super
puts 'child2'
end
end
Child2.new.go=20
----------------------------
in `go': undefined method `super' for nil:NilClass (NoMethodError)
----------------------------
I ended up doing this, which apprently works.
----------------------------
class Parent
def go
puts 'parent'
end
end
class Child1 < Parent
def go
super
puts 'child1'
end
def a_method_id_like_to_inherit
end
end
class Child2 < Child1
def go
self.class.superclass.superclass.instance_method( :go ).bind( self
).call=20
puts 'child2'
end
end
Child2.new.go=20
----------------------------
parent
child2
----------------------------
Isn't there anything simpler than that? Or is that kind of pattern
considered as bad design maybe?
Philippe
Let's say we have a Parent class, and a Child1 class that inherits from
the Parent class.
I'd like to create a Child2 class that inherits most of the Child1
class, except for one method, which I'd like to override completely. The
problem is that I need to call the method in the Parent class, and
apparently "super.super" is not supported:
----------------------------
class Parent
def go
puts 'parent'
end
end
class Child1 < Parent
def go
super
puts 'child1'
end
def a_method_id_like_to_inherit
end
end
class Child2 < Child1
def go
super.super
puts 'child2'
end
end
Child2.new.go=20
----------------------------
in `go': undefined method `super' for nil:NilClass (NoMethodError)
----------------------------
I ended up doing this, which apprently works.
----------------------------
class Parent
def go
puts 'parent'
end
end
class Child1 < Parent
def go
super
puts 'child1'
end
def a_method_id_like_to_inherit
end
end
class Child2 < Child1
def go
self.class.superclass.superclass.instance_method( :go ).bind( self
).call=20
puts 'child2'
end
end
Child2.new.go=20
----------------------------
parent
child2
----------------------------
Isn't there anything simpler than that? Or is that kind of pattern
considered as bad design maybe?
Philippe