Sha256: 4c1537487f89b0c1bbbed7f20fe24f95dae643cdc964f86deb0bcad30cc92e72

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

require 'dry/equalizer'
require 'dry/events/constants'

module Dry
  module Events
    # Event object
    #
    # @api public
    class Event
      include Dry::Equalizer(:id, :payload)

      DOT = '.'.freeze
      UNDERSCORE = '_'.freeze

      # @!attribute [r] id
      #   @return [Symbol] The event identifier
      attr_reader :id

      # Initialize a new event
      #
      # @param [Symbol] id The event identifier
      # @param [Hash] payload Optional payload
      #
      # @return [Event]
      #
      # @api private
      def initialize(id, payload = EMPTY_HASH)
        @id = id
        @payload = payload
      end

      # Get data from the payload
      #
      # @param [String,Symbol] name
      #
      # @api public
      def [](name)
        @payload.fetch(name)
      end

      # Coerce an event to a hash
      #
      # @return [Hash]
      #
      # @api public
      def to_h
        @payload
      end
      alias_method :to_hash, :to_h

      # Get or set a payload
      #
      # @overload
      #   @return [Hash] payload
      #
      # @overload payload(data)
      #   @param [Hash] data A new payload
      #   @return [Event] A copy of the event with the provided payload
      #
      # @api public
      def payload(data = nil)
        if data
          self.class.new(id, @payload.merge(data))
        else
          @payload
        end
      end

      # @api private
      def trigger?(query)
        query.empty? || query.all? { |key, value| payload[key] == value }
      end

      # @api private
      def listener_method
        @listener_method ||= :"on_#{id.to_s.gsub(DOT, UNDERSCORE)}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-events-0.1.0 lib/dry/events/event.rb