Module: Perennial::Dispatchable::InstanceMethods

Defined in:
lib/perennial/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



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/perennial/dispatchable.rb', line 57

def dispatch(name, opts = {})
  if !dispatching?
    Logger.debug "Dispatching #{name} event (#{dispatch_queue.size} queued - on #{self.class.name})"
    # Add ourselves to the queue
    @dispatching = true
    begin
      # 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.
      self.send(full_handler_name, opts) if self.respond_to?(full_handler_name)
      # 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
      Logger.info "Halting processing chain"
    rescue Exception => e
      Logger.log_exception(e)
    end
    @dispatching = false
    dispatch(*@dispatch_queue.shift) unless dispatch_queue.empty?
  else
    Logger.debug "Adding #{name} event to the end of the queue (on #{self.class.name})"
    dispatch_queue << [name, opts]
  end
end

#dispatch_queueObject



43
44
45
# File 'lib/perennial/dispatchable.rb', line 43

def dispatch_queue
  @dispatch_queue ||= []
end

#dispatching?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/perennial/dispatchable.rb', line 47

def dispatching?
  @dispatching ||= false
end

#handlersObject

Returns the handlers registered on this class, used inside dispatch.



39
40
41
# File 'lib/perennial/dispatchable.rb', line 39

def handlers
  self.class.handlers
end