Module: Observed::Hash::KeyPathEncoding
Instance Method Summary collapse
-
#at_key_path_on_hash(hash, key_path, options = {}) {|hash, key| ... } ⇒ Object
Decodes the key path such as ‘foo.bar’ to dig into the hash and returns ‘hash[:bar]`.
Instance Method Details
#at_key_path_on_hash(hash, key_path, options = {}) {|hash, key| ... } ⇒ Object
Decodes the key path such as ‘foo.bar’ to dig into the hash and returns ‘hash[:bar]`
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/observed/hash/key_path_encoding.rb', line 22 def at_key_path_on_hash(hash, key_path, = {}, &block) create_if_missing = [:create_if_missing] if create_if_missing.nil? fail "The key :create_if_missing must be exist in #{}" end if hash.nil? fail 'The hash must not be nil' end first, *rest = case key_path when Array key_path when String key_path.split(".") when Symbol key_path end key_str = first.to_s key_sym = first.intern key = if hash.key? key_str key_str else key_sym end if rest.empty? block.call hash, key else child = hash[key] if child at_key_path_on_hash(child, rest, , &block) elsif create_if_missing hash[key] = created = {} at_key_path_on_hash(created, rest, , &block) end end end |