jeudi 29 septembre 2016

How to update two arguments at the same time using Ruby Observer method?

I am studying Ruby's Design Pattern and came across Observer method. I tried to customize my own observer method to help me understand it but it returns an error. Here is what I came up with:

class YummyTastyDonut
    def update(changed_order)
        puts "Kitchen: Yo, change the order to #{changed_order.order}!"
        puts "Front: Order for #{changed_order.name}!"
        puts "Front: The price will now be #{changed_order.order_price} "
    end
end


class Customer
    attr_reader :name, :order
    attr_accessor :order_price

    def initialize(name, order, order_price)
        @name = name
        @order = order
        @order_price = order_price
        @observers = []
    end

    def order=(new_order, new_price)
        @order = new_order
        @order_price = new_price
        notify_observers
    end

    def notify_observers
        @observers.each do |observer|
            observer.update(self)
        end
    end

    def add_observer(observer)
        @observers << observer
    end

    def delete_observer(observer)
        @observers.delete(observer)
    end
end

If you read the book, I changed the class names, but the essence is the same. One thing I changed is order= method; it now accepts two arguments instead of one.

The goal is, after creating new Customer, I want the new customer to be able to change my order and notify YummyTastyDonut. However, I want to be able to update two things: the order and order_price (obviously, if I change my order, the price will also change). I want YummyTastyDonut to respond to my change.

igg = Customer.new("Iggy", "Bacon Donut", 10)
=> #<Customer:0x0056212e48a940 @name="Iggy", @order="Bacon Donut", @order_price=10, @observers=[]>

donut = YummyTastyDonut.new
=> #<YummyTastyDonut:0x0056212e4894c8>

## Updating my order and order_price ##

   igg.order = ("yummy butter donut", 15)
#(repl):1: syntax error, unexpected ',', expecting ')'
#igg.order = ("yummy butter donut", 15)

If I use this order= method that accepts only one argument, it works just as expected.

def order=(new_order)
    @order = new_order
    notify_observers
end

 igg.order = "Triple bacon donut explosion"
Kitchen: Yo, change the order to Triple bacon donut explosion!
Front: Order for Iggy!
Front: The price will now be 10 

What do I have to change so I can update both order and order_price simultaneously?

Aucun commentaire:

Enregistrer un commentaire