Class: AMQP::Events::ExternalEvent

Inherits:
Event
  • Object
show all
Defined in:
lib/amqp-events/event.rb

Overview

Represent external Event that can be subscribed to (by subscribers/observers). External means, it happens outside of this Ruby process, and is delivered through Transport. When Transport informs ExternalEvent that it happened (someplace else), ExternalEvent ‘fires’ and makes sure that all subscribers are called.

Any evented object (host) that defines ExternalEvent should provide it with transport either explicitly (via option :transport) or expose its own #transport.

Instance Attribute Summary collapse

Attributes inherited from Event

#host, #name, #subscribers

Instance Method Summary collapse

Methods inherited from Event

#==, #clear, create, #fire

Constructor Details

#initialize(host, name, opts) ⇒ ExternalEvent

Returns a new instance of ExternalEvent.



117
118
119
120
121
122
123
# File 'lib/amqp-events/event.rb', line 117

def initialize(host, name, opts)
  @routing = opts[:routing]
  @transport = opts[:transport] || host.transport rescue nil
  raise EventError.new "Unable to create ExternalEvent #{name.inspect} without routing" unless @routing
  raise EventError.new "Unable to create ExternalEvent #{name.inspect} without transport" unless @transport
  super host, name
end

Instance Attribute Details

#transportObject (readonly)

Returns the value of attribute transport.



115
116
117
# File 'lib/amqp-events/event.rb', line 115

def transport
  @transport
end

Instance Method Details

#subscribe(*args, &block) ⇒ Object

Subscribe to external event… Uses @host’s transport for actual subscription



126
127
128
129
130
# File 'lib/amqp-events/event.rb', line 126

def subscribe(*args, &block)
  super *args, &block
  @transport.subscribe(@routing) {|routing, data| fire(routing, data) } if @subscribers.size == 1
  self # This allows C#-like syntax : my_event += subscriber
end

#unsubscribe(name) ⇒ Object

Unsubscribe from external event… Cancels @host’s transport subscription if no subscribers left



133
134
135
136
137
# File 'lib/amqp-events/event.rb', line 133

def unsubscribe(name)
  super name
  @transport.unsubscribe(@routing) if @subscribers.empty?
  self # This allows C#-like syntax : my_event -= subscriber_name
end