Skip to content
Jeff Felchner edited this page Mar 6, 2023 · 2 revisions

As of Chamber 2.14.1, the preferred way of accessing Chamber's settings is via the dig!/dig methods.

dig!

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

Allows "Indifferent" Access To Settings

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'

dig

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
Clone this wiki locally