Polymorphic Ruby SimpleDelegator-Collection of common programming errors
What are the alternatives to the SimpleDelegator to leverage polymorphism without modifying underlying object.
This is an example and the problem that SimpleDelegator doesn’t solve.
The aim is to be able to wrap the original object (delicious_food) with any other (yak_food) so that the substituted method (delicious?) depends on the non-substituted methods of the underlying.
class Food
def initialize(color)
@color = color
end
def delicious?
color == :red
end
def color
@color
end
end
class FoodTasteOverride < SimpleDelegator
def color
:green
end
end
delicious_food = Food.new(:red)
yak_food = FoodTasteOverride.new delicious_food
delicious_food.delicious? # true - expected
yak_food.delicious? # expecting false, but is true since the color come from delicious_food
What would be the alternative that would actually use the substituted method? The contraint is that you can’t modify the underlying object, its class or clone.
The constraint implies that you can’t do this:
yak_food = delicious_food.clone
def yak_food.color
:green
end