Class: Observers::Key
- Inherits:
-
Object
- Object
- Observers::Key
- Defined in:
- lib/models/key.rb
Instance Attribute Summary collapse
-
#observers ⇒ Object
readonly
Returns the value of attribute observers.
Instance Method Summary collapse
-
#initialize(key:) ⇒ Key
constructor
A new instance of Key.
- #observe(object:, action:) ⇒ Object
-
#take(action: nil, event: nil) ⇒ Object
@returns: The result of the first observer with a non-nil value.
-
#trigger(action: nil, event: nil) ⇒ Object
@returns: The result of the last observer with a non-nil value.
Constructor Details
#initialize(key:) ⇒ Key
Returns a new instance of Key.
7 8 9 10 |
# File 'lib/models/key.rb', line 7 def initialize(key:) @key = key @observers = [] end |
Instance Attribute Details
#observers ⇒ Object (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
12 13 14 15 16 |
# File 'lib/models/key.rb', line 12 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: nil) ⇒ Object
@returns: The result of the first observer with a non-nil value.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/models/key.rb', line 37 def take(action: nil, event: nil) key_callback 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: nil) ⇒ Object
@returns: The result of the last observer with a non-nil value.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/models/key.rb', line 19 def trigger(action: nil, event: nil) key_callback 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 |