class SprayVent::Mediator
Object responsible for storing and triggering handlers associated to particular events.
This is the primarily used object when working Eventable.
Public Class Methods
Ensures that a collection of events is ready.
# File lib/spray_vent/mediator.rb, line 13 def initialize(target) @events = {} @target = target end
Public Instance Methods
Retrieves a collection of event handlers associated to the event_name passed.
@param event_name [String] the name of the event collection you are wanting to retrieve @param event_name [Symbol] the name of the event collection you are wanting to retrieve @return [Array]
# File lib/spray_vent/mediator.rb, line 40 def [](event_name) @events[event_name.to_sym] end
Adds an event handler attached to the event associated to name symbol.
Although this implementation allows passing multiple parameters only the 2nd parameter passed will be used and that value MUST respond_to :call.
@param name [String] the name of the event you want to invoke when @param args [Array] an array of arguments passed to the method @raises [Eventable::InvalidHandlerError]
# File lib/spray_vent/mediator.rb, line 26 def method_missing(name, *args) handler = block_given? ? Proc.new : args[0] raise invalid_handler if !handler.respond_to? :call name = name.to_sym @events[name] = [] if @events[name].nil? @events[name] << handler end
Will create an Eventable::Event associated to event_name and invoke all handlers associated to that event_name.
@param event_name [String] handlers associated to event name passed @param event_name [Symbol] handlers associated to event name passed @return [Eventable::Event]
# File lib/spray_vent/mediator.rb, line 50 def trigger(event_name, *args) name = event_name.to_sym # we are creating this outside of the unless block because we want to return the event every time event = SprayVent::Event.new name, @target, args unless @events[name].nil? @events[name].each do |handler| break if event.cancel? handler.call event end end end
Private Instance Methods
# File lib/spray_vent/mediator.rb, line 64 def invalid_handler InvalidHandlerError.new 'An object that responds to :call must be provided to Eventable::Mediator when adding event handlers' end