Module: OrangeZest::TriggerCondition

Defined in:
lib/orange_zest/trigger_condition.rb

Overview

Allows wrapping a boolean condition to monitor it for changes.

Constant Summary collapse

ON =
:on
OFF =
:off
@@states =
{}

Class Method Summary collapse

Class Method Details

.watch(condition) ⇒ Object

Watches the given boolean condition, and returns:

  • ON if the condition was previously false, and becomes true

  • OFF if the condition was previously true, and becomes false

  • ‘nil` if the condition has not changed

Conditions are assumed to be false on the first call.

Each separate condition is identified by its source file and line number, which means you **must not watch more than one condition on a single line**.

Parameters:

  • condition (Boolean)

    The condition to watch.

Returns:

  • The change in condition, if it has changed.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/orange_zest/trigger_condition.rb', line 22

def self.watch(condition)
  c = caller.first
  triggered = @@states[c]
  
  if (!condition && !triggered) || (condition && triggered)
    nil
  elsif condition && !triggered
    @@states[c] = true
    TriggerCondition::ON
  elsif !condition && triggered
    @@states[c] = false
    TriggerCondition::OFF
  else
    raise 'unexpected condition case'
  end
end