Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using Observable in Ruby
require 'observer'
class CoffeeShop
include Observable
attr_reader :customers
def initialize(name, capacity)
@name = name
@capacity = capacity
@customers = []
end
def enter(customer)
unless full?
changed
@customers.push(customer)
notify_observers(Time.now)
end
end
def depart(customer)
unless empty?
changed
@customers.delete(customer)
notify_observers(Time.now)
end
end
def full?
@customers.count >= @capacity
end
def empty?
@customers.count.zero?
end
end
class CoffeeShopObserver
def initialize(shop)
@shop = shop
@shop.add_observer(self)
end
end
class CoffeeShopEmptyObserver < CoffeeShopObserver
def update(time)
if @shop.empty?
puts "#{time}: The shop is EMPTY so some staff can go home."
end
end
end
class CoffeeShopFullObserver < CoffeeShopObserver
def update(time)
if @shop.full?
puts "#{time}: The shop is FULL - quick call more staff!"
end
end
end
coffee_shop = CoffeeShop.new("Costa", 3)
CoffeeShopEmptyObserver.new(coffee_shop)
CoffeeShopFullObserver.new(coffee_shop)
potential_customers = %w(Bob Harry William Darren Brian Susan Kelly John Kevin)
customer_actions = [:enter, :enter, :depart] #enter in twice to try and encourage more customers!
20.times do
action = customer_actions.sample
if action == :enter
customer = potential_customers.sample
potential_customers.delete(customer)
puts "Entering: #{customer}"
coffee_shop.enter(customer)
else
unless coffee_shop.empty?
customer = coffee_shop.customers.sample
puts "Leaving #{customer}"
potential_customers.push(customer)
coffee_shop.depart(customer)
end
end
sleep 0.1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.