Class: TokenOfFire::EventBus

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Celluloid
Defined in:
lib/token_of_fire/event_bus.rb

Instance Method Summary collapse

Constructor Details

#initializeEventBus

Returns a new instance of EventBus.



15
16
17
18
19
20
# File 'lib/token_of_fire/event_bus.rb', line 15

def initialize
  @subscriptions = TokenOfFire::Subscriptions.new
  @global_scope = TokenOfFire::Scope.new(Celluloid::Actor.current)
  @global_token = @global_scope.token
  self
end

Instance Method Details

#fire(event_name, payload, scope = nil) ⇒ Object



58
59
60
61
# File 'lib/token_of_fire/event_bus.rb', line 58

def fire(event_name, payload, scope=nil)
  scope ||= @global_scope.filter
  perform(event_name, scope, payload, :async)
end

#fire_sync(event_name, payload, scope = nil) ⇒ Object



63
64
65
66
# File 'lib/token_of_fire/event_bus.rb', line 63

def fire_sync(event_name, payload, scope=nil)
  scope ||= @global_scope.filter
  perform(event_name, scope, payload, :sync)
end

#make_event(event_name, scope, payload) ⇒ Object



68
69
70
# File 'lib/token_of_fire/event_bus.rb', line 68

def make_event(event_name, scope, payload)
  TokenOfFire::Event.new(event_name, scope, payload)
end

#perform(event_name, scope, payload, sync_type) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/token_of_fire/event_bus.rb', line 48

def perform(event_name, scope, payload, sync_type)
  event = make_event(event_name, scope, payload)
  case sync_type
    when :async
      async.trigger(event)
    when :sync
      trigger(event)
  end
end

#subscribe(event_name, scope, handler, handler_method) ⇒ Object



22
23
24
25
26
# File 'lib/token_of_fire/event_bus.rb', line 22

def subscribe(event_name, scope, handler, handler_method)
  uuid = @subscriptions.subscribe(event_name, scope, handler, handler_method)
  # $stdout.puts "-- Subscribe event_name: #{event_name} #{uuid}"
  uuid
end

#subscriptionsObject



33
34
35
# File 'lib/token_of_fire/event_bus.rb', line 33

def subscriptions
  @subscriptions.get_subscriptions
end

#trigger(event) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/token_of_fire/event_bus.rb', line 37

def trigger(event)
  subscriptions = @subscriptions.get_subscriptions(event.name, event.scope)
  if subscriptions and subscriptions.size > 0
    subscriptions.each_value do |subscription|
      subscription[:handler].send(subscription[:method_name], event.payload)
    end
  else
    # $stdout.puts "No subscriptions found for: scope: #{event.scope}, event_name: #{event.name}"
  end
end

#unsubscribe(uuid) ⇒ Object



28
29
30
31
# File 'lib/token_of_fire/event_bus.rb', line 28

def unsubscribe(uuid)
  # $stdout.puts "-- Unsubscribe uuid:#{uuid}"
  @subscriptions.unsubscribe(uuid)
end