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 =
"."
UNDERSCORE =
"_"

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)


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

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

Instance Attribute Details

#idObject (readonly)



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

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.



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

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

  raise InvalidEventNameError
end

Instance Method Details

#[](name) ⇒ Object

Get data from the payload

Parameters:

  • name (String, Symbol)


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

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.



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

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



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

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)


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

def to_h
  @payload
end