Class: Txgh::Events

Inherits:
Object
  • Object
show all
Defined in:
lib/txgh/events.rb

Constant Summary collapse

ERROR_CHANNEL =
'errors'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEvents

Returns a new instance of Events.



7
8
9
# File 'lib/txgh/events.rb', line 7

def initialize
  @channel_hash = Hash.new { |h, k| h[k] = [] }
end

Instance Attribute Details

#channel_hashObject (readonly)

Returns the value of attribute channel_hash.



5
6
7
# File 'lib/txgh/events.rb', line 5

def channel_hash
  @channel_hash
end

Instance Method Details

#channelsObject



23
24
25
# File 'lib/txgh/events.rb', line 23

def channels
  channel_hash.keys
end

#publish(channel, options = {}) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/txgh/events.rb', line 15

def publish(channel, options = {})
  channel_hash.fetch(channel, []).each do |callback|
    callback.call(options)
  end
rescue => e
  publish_error(e)
end

#publish_error(e) ⇒ Object



27
28
29
30
31
# File 'lib/txgh/events.rb', line 27

def publish_error(e)
  # if nobody has subscribed to error events, raise original error
  callbacks = channel_hash.fetch(ERROR_CHANNEL) { raise e }
  callbacks.each { |callback| callback.call(e) }
end

#subscribe(channel, &block) ⇒ Object



11
12
13
# File 'lib/txgh/events.rb', line 11

def subscribe(channel, &block)
  channel_hash[channel] << block
end