[Ruby] How to call back from superclass to subclass?
Posted: Wed Mar 14, 2018 7:09 am
Ok, it isn't obvious what I'm looking for. So I try to use an example that is as close to a real world issue, as I can think of, while keeping it simple.
You have a class for centered coordinates. It defines a setter method.
A second class inherits A and uses x to calculate the top-left position.
Now, to actually do the update, I have to wait for x to change. If that happens, update is called afterwards. And here's where it gets ugly. Implementation:
I don't like that for two reasons:
1) defining x=(value) two times (I think it's called monkey patching) shouldn't be necessary in such an elegant language.
2) The update method in reality is a general updater, that not only updates @l, but some other variables as well. The superclass does not just host @x, but a lot of other variables. In effect, I need to define the setter two times for each of them, always with a call of update()
What I'm looking for, is a way to signalize the subclass, that a superclass method has been called, so that I can run update()
PSEUDOCODE!
Any ideas?
You have a class for centered coordinates. It defines a setter method.
Code: Select all
class A
def initialize
@x = 0.0
end
def x=(value)
@x = value
end
endA second class inherits A and uses x to calculate the top-left position.
Code: Select all
class B < A
def initialize
@l = 0.0
end
def update
@l = @x - 2
end
endNow, to actually do the update, I have to wait for x to change. If that happens, update is called afterwards. And here's where it gets ugly. Implementation:
Code: Select all
class B < A
def initialize
@l = 0.0
end
def update
@l = @x - 2
end
def x=(value)
super(value)
update
end
endI don't like that for two reasons:
1) defining x=(value) two times (I think it's called monkey patching) shouldn't be necessary in such an elegant language.
2) The update method in reality is a general updater, that not only updates @l, but some other variables as well. The superclass does not just host @x, but a lot of other variables. In effect, I need to define the setter two times for each of them, always with a call of update()
What I'm looking for, is a way to signalize the subclass, that a superclass method has been called, so that I can run update()
PSEUDOCODE!
Code: Select all
class B < A
def initialize
@l = 0.0
end
def update
@l = @x - 2
end
def message_from_super
update()
end
endAny ideas?