Module: Marvin::Dispatchable::InstanceMethods

Defined in:
lib/marvin/dispatchable.rb

Instance Method Summary collapse

Instance Method Details

#dispatch(name, opts = {}) ⇒ Object

Dispatch an ‘event’ with a given name to the handlers registered on the current class. Used as a nicer way of defining behaviours that should occur under a given set of circumstances.

Params

name: The name of the current event opts: an optional hash of options to pass



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/marvin/dispatchable.rb', line 42

def dispatch(name, opts = {})
  # The full handler name is the method we call given it exists.
  full_handler_name = :"handle_#{name.to_s.underscore}"
  # First, dispatch locally if the method is defined.
  if self.respond_to?(full_handler_name)
    self.send(full_handler_name, opts)
  end
  # Iterate through all of the registered handlers,
  # If there is a method named handle_<event_name>
  # defined we sent that otherwise we call the handle
  # method on the handler. Note that the handle method
  # is the only required aspect of a handler. An improved
  # version of this would likely cache the respond_to?
  # call.
  self.handlers.each do |handler|
    if handler.respond_to?(full_handler_name)
      handler.send(full_handler_name, opts)
    else
      handler.handle name, opts
    end
  end
# If we get the HaltHandlerProcessing exception, we
# catch it and continue on our way. In essence, we
# stop the dispatch of events to the next set of the
# handlers.
rescue HaltHandlerProcessing => e
  Marvin::Logger.info "Halting processing chain"
rescue Exception => e
  Marvin::ExceptionTracker.log(e)
end

#handlersObject

Returns the handlers registered on this class, used inside dispatch. Note that it will call dup on each of the objects to get a new instance. please ensure your object acts accordingly.



32
33
34
# File 'lib/marvin/dispatchable.rb', line 32

def handlers
  @handlers ||= self.class.handlers.map { |h| h.dup }
end