module HashAtPath::CoreExt::Hash::AtPath

Public Instance Methods

at_path(path) click to toggle source

Returns a value at the end of an xpath-like/lite path

# File lib/hash_at_path/core_ext/hash/at_path.rb, line 6
def at_path(path)
  if path == '/'
      self
  else
    extract(self, path)
  end
end

Private Instance Methods

extract(val, path_string) click to toggle source
# File lib/hash_at_path/core_ext/hash/at_path.rb, line 16
def extract(val, path_string)
  predicate = nil
  Path.parse(path_string).each do |path_parts|
    return nil if val.nil?
    predicate = path_parts[:predicate] unless predicate == '*'
    val, predicate = get_value_at_path(predicate, path_parts[:path], val)
    val = val[predicate.to_i] unless is_blank?(predicate) || predicate == '*' || !issa(val, 'Array')
  end
  val
end
get_value_at_path(predicate, path, val) click to toggle source
# File lib/hash_at_path/core_ext/hash/at_path.rb, line 27
def get_value_at_path(predicate, path, val)
  if predicate == '*' && issa(val, 'Array') && !is_blank?(path)
    val = val.map {|item| unwind_path(item, path)}
    predicate = nil
  elsif !is_blank?(path) && issa(val, 'Hash')
    val = unwind_path(val, path)
  end
  [val, predicate]
end
is_blank?(object) click to toggle source

Stolen from activesupport/lib/active_support/core_ext/object/blank.rb

# File lib/hash_at_path/core_ext/hash/at_path.rb, line 51
def is_blank?(object)
  object.respond_to?(:empty?) ? !!object.empty? : !object
end
issa(item, classname) click to toggle source
# File lib/hash_at_path/core_ext/hash/at_path.rb, line 37
def issa(item, classname)
  item.class.to_s == classname
end
path_keys(path) click to toggle source

Be nice: remove empty path items (e.g. when we get a leading slash)

# File lib/hash_at_path/core_ext/hash/at_path.rb, line 46
def path_keys(path)
  path.split("/").reject { |c| c.empty? }
end
unwind_path(val, path) click to toggle source
# File lib/hash_at_path/core_ext/hash/at_path.rb, line 41
def unwind_path(val, path)
  path_keys(path).inject(val) { |item, path_key| (issa(item, 'Hash')) ? item.fetch(path_key, nil) : nil}
end