Class: Observers::Observer

Inherits:
Object
  • Object
show all
Defined in:
lib/models/observer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object:, action:) ⇒ Observer

Returns a new instance of Observer.



7
8
9
10
# File 'lib/models/observer.rb', line 7

def initialize(object:, action:)
  @object = object
  @action = action
end

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



5
6
7
# File 'lib/models/observer.rb', line 5

def action
  @action
end

#objectObject (readonly)

Returns the value of attribute object.



5
6
7
# File 'lib/models/observer.rb', line 5

def object
  @object
end

Instance Method Details

#trigger(action:, event:) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/models/observer.rb', line 12

def trigger(action:, event:)
  action = @action if @action
  event ? @object.send(action, **{ event: }) : @object.send(action)
rescue ArgumentError => e
  type = @object.instance_of?(Class) ? @object : @object.class
  method_type = @object.instance_of?(Class) ? '.' : '#'

  raise ArgumentError, "#{type}##{action} has an 'event:' keyword argument but no event arg was sent" if event.nil?

  # Events trigger events, so the error bubbles up to becomes the error message for the next rescue's error message:
  # "RequestEvent sent to Rain::Router#handle -> StatusEvent sent to Error404Node.render -> unknown keyword: :props"
  raise ArgumentError, "#{event.class} sent to #{type}#{method_type}#{action} -> #{e.message}"
end