Module: Emittance::Emitter::ClassAndInstanceMethods

Defined in:
lib/emittance/emitter.rb

Overview

Included and extended whenever Emittance::Emitter is extended.

Instance Method Summary collapse

Instance Method Details

#emit(identifier, payload: nil) ⇒ Object

Emits an event object to watchers.

Parameters:

  • identifier (Symbol, Emittance::Event)

    either an explicit Event object or the identifier that can be parsed into an Event object.

  • payload (*) (defaults to: nil)

    any additional information that might be helpful for an event’s handler to have. Can be standardized on a per-event basis by pre-defining the class associated with the identifier and validating the payload. See Emittance::Event for more details.

  • broker (Symbol)

    the identifier for the broker you wish to handle the event. Requires additional gems if not using the default.

Returns:

  • the payload



65
66
67
68
69
70
71
72
# File 'lib/emittance/emitter.rb', line 65

def emit(identifier, payload: nil)
  now = Time.now
  event_klass = _event_klass_for identifier
  event = event_klass.new(self, now, payload)
  _send_to_broker event

  payload
end

#emit_with_dynamic_identifier(*identifiers, payload:) ⇒ Object

If you don’t know the specific identifier whose event you want to emit, you can send it a bunch of stuff and Emitter will automatically generate an Event class for you.

Parameters:

  • identifiers (*)

    anything that can be used to generate an Event class.

  • payload (@see #emit)
  • broker (@see #emit)


80
81
82
83
84
85
86
87
# File 'lib/emittance/emitter.rb', line 80

def emit_with_dynamic_identifier(*identifiers, payload:)
  now = Time.now
  event_klass = _event_klass_for(*identifiers)
  event = event_klass.new(self, now, payload)
  _send_to_broker event

  payload
end

#emits_on(*method_names, identifier: nil) ⇒ Object

Tells the object to emit an event when a any of the given set of methods. By default, the event classes are named accordingly: If a Foo object emits_on :bar, then the event’s class will be named FooBarEvent, and will be a subclass of Emittance::Event.

The payload for this event will be the value returned from the method call.

Parameters:

  • method_names (Symbol, String, Array<Symbol, String>)

    the methods whose calls emit an event



96
97
98
99
100
101
102
# File 'lib/emittance/emitter.rb', line 96

def emits_on(*method_names, identifier: nil)
  method_names.each do |method_name|
    non_emitting_method = Emittance::Emitter.non_emitting_method_for method_name

    Emittance::Emitter.emitter_eval(self, &_method_patch_block(method_name, non_emitting_method, identifier))
  end
end