class PaymentHandler
attr_accessor :successor
def initialize(successor = nil)
@successor = successor
end
def call(price)
successor ? successor.call(price) : error
end
private
def success(message)
message
end
def error
"You are poor and have nothing to pay!"
end
end
class VoucherPaymentHandler < PaymentHandler
def call(price)
price < 20 ? success('You paid by Voucher!') : super(price)
end
end
class CashPaymentHandler < PaymentHandler
def call(price)
price < 100 ? success('You paid by Cash!') : super(price)
end
end
class CardPaymentHandler < PaymentHandler
def call(price)
price < 200 ? success('You paid by Card!') : super(price)
end
end
payment = VoucherPaymentHandler.new(
CashPaymentHandler.new(
CardPaymentHandler.new
)
)
payment.call(10) => "You paid by Voucher!"
payment.call(50) => "You paid by Cash!"
payment.call(150) => "You paid by Card!"
payment.call(420) => "You are poor and have nothing to pay!"