I want to create an instance method that changes its behavior with the return value of another method depending on the implementation of it being rewritable in a polymorphic way.
For example, it is assumed that the next class will be extended and pricing_ruleshould vary from product to product.
class Purchase
def discount_price
prices = [100, 200, 300]
pricing_rule.call
end
protected
def pricing_rule
Proc.new do
rate = prices.size > 2 ? 0.8 : 1
total = prices.inject(0){|sum, v| sum += v}
total * rate
end
end
end
Purchase.new.discount_price
But I run the local error of the undefined variable at startup. Although I understand that the Proc instance refers to the Purchase instance, I sometimes encountered similar situations, I need to place the variable pricesin the discount_price method. Is there a smarter way to reference a local variable in a Proc caller?
source
share