Sha256: 9bfabe7844cb90ad4401ff8f86d70c08933d23300adead4d90a8ff704459e916

Contents?: true

Size: 1.81 KB

Versions: 5

Compression:

Stored size: 1.81 KB

Contents

module Vedeu

  # Trigger a registered or system event by name with arguments. If the
  # event stored returns a value, that is returned. If multiple events are
  # registered for a name, then the result of each event will be returned as
  # part of a collection.
  #
  # @example
  #   Vedeu.trigger(:my_event, :oxidize, 'nitrogen')
  #
  class Trigger

    # @param name [Symbol] The name of the event you wish to trigger. The event
    #   does not have to exist.
    # @param args [Array] Any arguments the event needs to execute correctly.
    # @return [Array]
    def self.trigger(name, *args)
      new(name, *args).trigger
    end

    # Returns a new instance of Vedeu::Trigger.
    #
    # @param (see .trigger)
    # @return [Vedeu::Trigger]
    def initialize(name, *args)
      @name = name
      @args = args
      @repository = Vedeu.events
    end

    # Trigger the event and return the result or an array of results.
    #
    # @return [Array]
    def trigger
      if results.one?
        results.first

      else
        results

      end
    end

    protected

    # @!attribute [r] name
    # @return [Symbol]
    attr_reader :name

    # @!attribute [r] args
    # @return [Array]
    attr_reader :args

    # @!attribute [r]
    # @return [Vedeu::Repository]
    attr_reader :repository

    private

    # @return [Array<void>|void]
    def results
      @results ||= registered_events.map { |event| event.trigger(*args) }
    end

    # Return all of the registered events for this name.
    #
    # @return [Array|Array<Vedeu::Event>]
    def registered_events
      if repository.registered?(name)
        repository.find(name)

      else
        Vedeu::EventAliases.find(name).map do |event_name|
          Vedeu::Trigger.trigger(event_name, *args)
        end

        []

      end
    end

  end # Trigger

end # Vedeu

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
vedeu-0.5.6 lib/vedeu/events/trigger.rb
vedeu-0.5.5 lib/vedeu/events/trigger.rb
vedeu-0.5.4 lib/vedeu/events/trigger.rb
vedeu-0.5.3 lib/vedeu/events/trigger.rb
vedeu-0.5.2 lib/vedeu/events/trigger.rb