Class: Pub::Patron

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/pub/patron.rb

Overview

A patron.

In other words, a consumer in our processing queue.

Instance Method Summary collapse

Constructor Details

#initialize(pub_name, timeout) ⇒ Patron

Creates a new pub patron.

Takes the name of the pub and a timeout value in seconds.

The timeout designates how long a patron is willing to wait at the counter to receive his or her beer.



14
15
16
# File 'lib/pub/patron.rb', line 14

def initialize(pub_name, timeout)
  @pub_name, @timeout = pub_name, timeout
end

Instance Method Details

#order(*beers) ⇒ Object

 Orders one or more beer at the bar counter.

If given a block, yields beers as they become available. Otherwise, returns all on a tray.

If not all beers are served within specified timeout, it will return only the beers that are ready.

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pub/patron.rb', line 25

def order(*beers)
  raise ArgumentError, 'Empty order' if beers.empty?

  orders, tray = [], []

  beers.flatten!

  beers.each do |beer|
    counter.rpush(@pub_name, beer)
    orders << order_for(beer)
  end

  timer = EM.add_timer(@timeout) do
    foo = counter.unsubscribe
  end

  counter.subscribe(*orders) do |on|
    on.message do |order, beer|
      counter.unsubscribe(order)
      if block_given?
        yield beer
      else
        tray << beer
      end
    end
  end

  EM.cancel_timer(timer)
  block_given? ? nil : tray
end