Skip to content

Instantly share code, notes, and snippets.

@aschyiel
Created October 17, 2016 23:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aschyiel/04136beaaede45b695b97b4cb3cc2b96 to your computer and use it in GitHub Desktop.
Save aschyiel/04136beaaede45b695b97b4cb3cc2b96 to your computer and use it in GitHub Desktop.
A ruby analog of lodash#get.
module MyModuleName
# Safely navigate a hashmap via dot-notation, similar to lodash#get.
# May return nil; Assumes string keys, will not work for symbols!
#
# Example Usage:
# got(foo, 'bar.fizz.buzz')
def got(object, dot_notation_path, default_value = nil)
# FIXME: Does not support OpenStruct! -uly, july 2016
keys = dot_notation_path.split('.')
while !keys.empty? && !object.nil?
object = object.is_a?(Array) ? nil : object.try(:fetch, keys.shift, nil)
end
object.nil? ? default_value : object
end
end
@aschyiel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment