Skip to main content Link Search Menu Expand Document (external link)

SwitchItem

MethodDescriptionExample
truthy?Item is not undefined, not null and is ONputs "#{item.name} is truthy" if item.truthy?
onSend command to turn item ONitem.on
offSend command to turn item OFFitem.off
on?Returns true if item state == ONputs "#{item.name} is on." if item.on?
off?Returns true if item state == OFFputs "#{item.name} is off." if item.off?
toggleSend command to invert the state of the itemitem.toggle
!Return the inverted state of the itemitem << !item

Switches respond to on, off, and toggle

# Turn on all switches in a `Group:Switch` called Switches
Switches.on

Check state with off? and on?

# Turn on all switches in a group called Switches that are off
Switches.select(&:off?).each(&:on)

Switches can be selected in an enumerable with grep.

items.grep(SwitchItem)
     .each { |switch| logger.info("Switch #{switch.id} found") }

Switch states also work in grep.

# Log all switch items set to ON
items.grep(SwitchItem)
     .grep(ON)
     .each { |switch| logger.info("#{switch.id} ON") }

# Log all switch items set to OFF
items.grep(SwitchItem)
     .grep(OFF)
     .each { |switch| logger.info("#{switch.id} OFF") }

Switches accept boolean commands (true/false)

# Turn on switch
SwitchItem << true

# Turn off switch
SwitchItem << false

# Turn off switch if any in another group is on
SwitchItem << Switches.any?(&:on?)

Switch states also work in case statements.

items.grep(SwitchItem)
     .each do |switch|
        case switch
        when ON
          logger.info("#{switch.id} ON")
        when OFF
          logger.info("#{switch.id} OFF")
         end
      end

Other examples

# Invert all switches
items.grep(SwitchItem)
     .each { |item| if item.off? then item.on else item.off end}

# Or using not operator

items.grep(SwitchItem)
     .each { |item| item << !item }