Class: Holistic::Extensions::Events
- Inherits:
-
Object
- Object
- Holistic::Extensions::Events
- Defined in:
- lib/holistic/extensions/events.rb
Constant Summary collapse
- TOPICS =
{ resolve_method_call_known_scope: { params: [:reference, :referenced_scope, :method_call_clue], output: ::Holistic::Ruby::Scope::Record }, class_scope_registered: { params: [:class_scope, :location], output: nil }, lambda_scope_registered: { params: [:lambda_scope, :location], output: nil } }.freeze
- UnknownEvent =
::Class.new(::StandardError)
- MissingRequiredParam =
::Class.new(::StandardError)
- UnexpectedOutput =
::Class.new(::StandardError)
Instance Method Summary collapse
- #bind(event, &callback) ⇒ Object
- #dispatch(event, params) ⇒ Object
-
#initialize ⇒ Events
constructor
A new instance of Events.
Constructor Details
#initialize ⇒ Events
Returns a new instance of Events.
23 24 25 |
# File 'lib/holistic/extensions/events.rb', line 23 def initialize @listeners = Hash.new { |hash, key| hash[key] = [] } end |
Instance Method Details
#bind(event, &callback) ⇒ Object
27 28 29 30 31 |
# File 'lib/holistic/extensions/events.rb', line 27 def bind(event, &callback) raise UnknownEvent, event unless TOPICS.key?(event) @listeners[event] << callback end |
#dispatch(event, params) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/holistic/extensions/events.rb', line 33 def dispatch(event, params) required_params = TOPICS.dig(event, :params) expected_output = TOPICS.dig(event, :output) raise MissingRequiredParam, required_params if (required_params - params.keys).any? result = @listeners[event].lazy.filter_map { |callback| callback.call(params) }.first raise UnexpectedOutput, result if expected_output.present? && result.present? && !result.is_a?(expected_output) result end |