Class: Dry::Events::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/events/event.rb

Overview

Event object

Constant Summary collapse

InvalidEventNameError =
Class.new(StandardError) do
  # @api private
  def initialize
    super("please provide a valid event name, it could be either String or Symbol")
  end
end
DOT =
'.'.freeze
UNDERSCORE =
'_'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, payload) ⇒ Event

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a new event

Parameters:

  • id (Symbol, String)

    The event identifier

  • payload (Hash)

41
42
43
44
# File 'lib/dry/events/event.rb', line 41

def initialize(id, payload)
  @id = id
  @payload = payload
end

Instance Attribute Details

#idObject (readonly)


24
25
26
# File 'lib/dry/events/event.rb', line 24

def id
  @id
end

Class Method Details

.new(id, payload = EMPTY_HASH) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


27
28
29
30
31
# File 'lib/dry/events/event.rb', line 27

def self.new(id, payload = EMPTY_HASH)
  return super(id, payload) if (id.is_a?(String) || id.is_a?(Symbol)) && !id.empty?

  raise InvalidEventNameError.new
end

Instance Method Details

#[](name) ⇒ Object

Get data from the payload

Parameters:

  • name (String, Symbol)

51
52
53
# File 'lib/dry/events/event.rb', line 51

def [](name)
  @payload.fetch(name)
end

#listener_methodObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


84
85
86
# File 'lib/dry/events/event.rb', line 84

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

#Hash #payload(data) ⇒ Event

Get or set a payload

Overloads:

  • #Hash

    Returns payload.

    Returns:

    • (Hash)

      payload

  • #payload(data) ⇒ Event

    Returns A copy of the event with the provided payload.

    Parameters:

    • data (Hash)

      A new payload

    Returns:

    • (Event)

      A copy of the event with the provided payload


75
76
77
78
79
80
81
# File 'lib/dry/events/event.rb', line 75

def payload(data = nil)
  if data
    self.class.new(id, @payload.merge(data))
  else
    @payload
  end
end

#to_hHash Also known as: to_hash

Coerce an event to a hash

Returns:

  • (Hash)

60
61
62
# File 'lib/dry/events/event.rb', line 60

def to_h
  @payload
end