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



26
27
28
# File 'lib/txgh/events.rb', line 26

def channels
  channel_hash.keys
end

#publish(channel, options = {}) ⇒ Object Also known as: publish_each



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

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

#publish_error(e, params = {}) ⇒ Object



30
31
32
33
# File 'lib/txgh/events.rb', line 30

def publish_error(e, params = {})
  callbacks = channel_hash.fetch(ERROR_CHANNEL) { [] }
  callbacks.map { |callback| callback.call(e, params) }
end

#publish_error!(e, params = {}) ⇒ Object



35
36
37
38
39
# File 'lib/txgh/events.rb', line 35

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

#subscribe(channel, &block) ⇒ Object



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

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