Class: WindUp::Router::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/wind_up/routers.rb

Direct Known Subclasses

FirstAvailable, Random, RoundRobin, SmallestMailbox

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



24
25
26
# File 'lib/wind_up/routers.rb', line 24

def initialize
  @mutex = Mutex.new
end

Instance Method Details

#<<(message) ⇒ Object

Send the call to all subscribers



50
51
52
53
54
55
56
57
58
# File 'lib/wind_up/routers.rb', line 50

def <<(message)
  @mutex.lock
  begin
    target = next_subscriber
    send_message(target, message) if target
  ensure
    @mutex.unlock rescue nil
  end
end

#add_subscriber(subscriber) ⇒ Object

Subscribe to this mailbox for updates of new messages

Parameters:

  • subscriber (Object)

    the subscriber to send messages to



35
36
37
38
39
# File 'lib/wind_up/routers.rb', line 35

def add_subscriber(subscriber)
  @mutex.synchronize do
    subscribers << subscriber unless subscribers.include?(subscriber)
  end
end

#broadcast(message) ⇒ Object



60
61
62
# File 'lib/wind_up/routers.rb', line 60

def broadcast(message)
  send_message(subscribers, message)
end

#remove_subscriber(subscriber) ⇒ Object

Remove a subscriber from thie mailbox

Parameters:

  • subscriber (Object)

    the subscribed object



43
44
45
46
47
# File 'lib/wind_up/routers.rb', line 43

def remove_subscriber(subscriber)
  @mutex.synchronize do
    subscribers.delete subscriber
  end
end

#send_message(target, message) ⇒ Object

Send a message to the specified target



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/wind_up/routers.rb', line 65

def send_message(target, message)
  # Array-ize unless we're an Enumerable already that isn't a Mailbox
  target = [target] unless target.is_a?(Enumerable) && !target.respond_to?(:receive)

  target.each do |targ|
    begin
      targ << message
    rescue Celluloid::MailboxError
      # Mailbox died, remove subscriber
      remove_subscriber targ
    end
  end
  nil
end

#subscribersObject

List all subscribers



29
30
31
# File 'lib/wind_up/routers.rb', line 29

def subscribers
  @subscribers ||= []
end