Class: Txgh::Events
- Inherits:
-
Object
- Object
- Txgh::Events
- Defined in:
- lib/txgh/events.rb
Constant Summary collapse
- ERROR_CHANNEL =
'errors'
Instance Attribute Summary collapse
-
#channel_hash ⇒ Object
readonly
Returns the value of attribute channel_hash.
Instance Method Summary collapse
- #channels ⇒ Object
-
#initialize ⇒ Events
constructor
A new instance of Events.
- #publish(channel, options = {}) ⇒ Object (also: #publish_each)
- #publish_error(e, params = {}) ⇒ Object
- #publish_error!(e, params = {}) ⇒ Object
- #subscribe(channel, &block) ⇒ Object
Constructor Details
#initialize ⇒ Events
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_hash ⇒ Object (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
#channels ⇒ Object
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, = {}) channel_hash.fetch(channel, []).each do |callback| result = callback.call() 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 |