Project

fat

0.01
No commit activity in last 3 years
No release in over 3 years
C extension to find values in nested hashes without pain
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

 Project Readme

fat

Fat is where dig meets fetch

The name is an acronym for "find at". It helps you avoid that nasty undefined method [] for nil when looking for values in a hash.

Why

Say you have the following hash

hash = {
  "foo" => {
    "bar" => {
      "baz" => :value
    }
  }
}

To get your :value you usually do hash["foo"]["bar"]["baz"]. But what happens if "bar" doesn't exist? Yeap, BOOM! You will get an undefined method [] for nil error.

Use

Using Fat you can walk the hash up to the :value (just like dig), but it'll raise an exception if it finds nil (just like fetch) at any point.

require "fat"

Fat.at(hash, "foo", "bar", "baz")
# => :value

Fat.at(hash, "foo", "not", "here")
# => Fat::FatError: foo.not is nil

Fat.at(hash, "foo", "bar", "nope")
# => Fat::FatError: foo.bar.nope is nil

You can specify a default return value with the default: keyword if you don't want an exception raised.

require "fat"

Fat.at(hash, "foo", "not", "here", default: "whoops")
# => "whoops"

If you set default: nil this method behaves exactly like Hash#dig, available from Ruby 2.3.0.

It's the same with Symbols

hash = {
  "foo" => {
    :bar => {
      "baz" => :value
    }
  }
}

Fat.at(hash, "foo", :bar, "baz")
# => :value

If you prefer to call hash.at you only need to include Fat into Hash.

Hash.include(Fat)

hash.at("foo", "bar", "baz")
# => :value

Install

$ gem install fat