-
-
Notifications
You must be signed in to change notification settings - Fork 25
Dig
As of Chamber 2.14.1
, the preferred way of accessing Chamber's settings is via
the dig!
/dig
methods.
This works similarly to Hash#dig
except that it will raise an
exception if you try to access an element that does not exist. When working
with configuration objects, this is almost exclusively what you're going to want
to use. You don't want to take the chance that a misspelling gives you a value
that works in development or on CI but doesn't work in production and you can't
figure out why.
my_setting:
my_inner_setting:
- my_array_item: "hello"
other_array_item: "dawn"
Chamber.dig!('my_setting', 'my_inner_setting', 0, 'my_array_item')
# => 'hello'
Chamber.dig!('my_setting', 'my_inner_setting', 0)
# => {
# my_array_item: "hello",
# other_array_item: "dawn",
# }
Chamber.dig!('my_setting', 'my_inner_setting', 2)
# raises an `IndexError` because the array only contains 2 items
Chamber.dig!('my_setting', 'my_unknown_setting', 0)
# raises a `KeyError` because `my_unknown_setting` does not exist
Much like ActiveSupport's HashWithIndifferentAccess
, you can use dig with
either Symbols or Strings and it will pull the correct value.
However, one big difference is that under the hood, the settings data only ever contains string keys so this is truely "indifferent access" and not "indifferent storage".
my_setting:
my_inner_setting:
- my_array_item: "hello"
other_array_item: "dawn"
Chamber.dig!(:my_setting, :my_inner_setting, 0, :my_array_item)
# => 'hello'
You may also mix and match if there is some need to do that:
Chamber.dig!(:my_setting, 'my_inner_setting', 0, 'my_array_item')
# => 'hello'
This method is identical to dig!
with the exception that unknown or
non-existent keys will not blow up and will instead return nil
. Use this
method in production with extreme caution.
my_setting:
my_inner_setting:
- my_array_item: "hello"
other_array_item: "dawn"
Chamber.dig('my_setting', 'my_inner_setting', 0, 'my_array_item') # => 'hello'
Chamber.dig('my_setting', 'my_inner_setting', 2) # => nil
Chamber.dig('my_setting', 'my_unknown_setting', 0) # => nil
Copyright ©2023
- Release News
- Gem Comparison
- 12-Factor App Rebuttal
- Environment Variable Problems
- Installation
- Basics
- Defining Settings
- Accessing Settings
- Verifying Settings
- Namespaces
- Environment Variables
- Integrations
- Encryption
- Advanced Usage
- Command Line Reference