Skip to content

Predicate Methods

Jeff Felchner edited this page Dec 30, 2020 · 3 revisions

When using object notation, all settings have ? and _ predicate methods defined on them. They work like so:

'?' Predicates Check For Falsity

This predicate returns true for anything except false, nil, or a non-existent key.

  Chamber.env.my_setting                    # => nil
  Chamber.env.my_setting?                   # => false

  Chamber.env.my_other_setting              # => false
  Chamber.env.my_other_setting?             # => false

  Chamber.env.another_setting               # => 'my value'
  Chamber.env.another_setting?              # => true

  Chamber.env.this_setting_does_not_exist?  # => false

'key?' Checks For Existence

While the ? method will return false if a key has been set to false or nil. In order to check if a key has been set at all, use the key?('some_key') method instead.

Notice the difference:

  Chamber.env.my_setting                    # => false
  Chamber.env.my_setting?                   # => false

  Chamber.env.key?('my_setting')            # => true
  Chamber.env.key?('my_non_existent_key')   # => false

'?' vs 'key?'

Value ? key?
unset false false
nil false true
false false true
true true true
'hi' true true

'_' Predicates Allow for Multi-Level Testing

This predicate allows for similar functionality to Hash#dig.

  Chamber.env.empty?                        # => true

  Chamber.env.my_setting_group_.my_setting? # => false
Clone this wiki locally