Class: Observers::Key

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeKey

Returns a new instance of Key.



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

def initialize
  @observers = []
end

Instance Attribute Details

#observersObject (readonly)

Returns the value of attribute observers.



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

def observers
  @observers
end

Instance Method Details

#observe(object:, action:) ⇒ Object



11
12
13
14
15
# File 'lib/models/key.rb', line 11

def observe(object:, action:)
  # TODO: We can observe objects directly, no need to wrap in an observer... no need to let the object's observer override the action?
  # A future reason I can think of for keeping observer wrapper is to track whether the object has implemented certain actions/methods.
  @observers << Observer.new(object:, action:)
end

#take(action: nil, event:) ⇒ Object

@returns: The result of the first observer with a non-nil value.



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/models/key.rb', line 34

def take(action: nil, event:)
  action = event.action if event && action.nil?
  action = :handle if action.nil?

  @observers.each do |observer|
    result = observer.trigger(action:, event:)
    yield if block_given?
    return result unless result.nil?
  end

  nil # This is a bad day for the take method, one of the worst.
end

#trigger(action: nil, event:) ⇒ Object

@returns: The result of the last observer with a non-nil value.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/models/key.rb', line 18

def trigger(action: nil, event:)
  action = event.action if event && action.nil?
  action = :handle if action.nil?

  last_result = nil

  @observers.each do |observer|
    result = observer.trigger(action:, event:)
    last_result = result unless result.nil?
    yield if block_given?
  end

  last_result
end