module MoreCoreExtensions::Shared::Nested

Public Instance Methods

delete_path(*args) click to toggle source
# File lib/more_core_extensions/core_ext/shared/nested.rb, line 5
def delete_path(*args)
  args = args.first if args.length == 1 && args.first.kind_of?(Array)
  raise ArgumentError, "must pass at least one key" if args.empty?

  key = args.first
  raise ArgumentError, "must be a number" if self.kind_of?(Array) && !key.kind_of?(Numeric)

  child = self[key]
  if args.length == 1 || !child.respond_to?(:delete_path)
    self.kind_of?(Array) ? self.delete_at(key) : self.delete(key)
  else
    child.delete_path(args[1..-1])
  end
end
fetch_path(*args) click to toggle source
# File lib/more_core_extensions/core_ext/shared/nested.rb, line 20
def fetch_path(*args)
  args = args.first if args.length == 1 && args.first.kind_of?(Array)
  raise ArgumentError, "must pass at least one key" if args.empty?

  key = args.first
  raise ArgumentError, "must be a number" if self.kind_of?(Array) && !key.kind_of?(Numeric)

  child = self[key]
  return child if args.length == 1
  return nil unless child.respond_to?(:fetch_path)
  return child.fetch_path(args[1..-1])
end
find_path(val) click to toggle source
# File lib/more_core_extensions/core_ext/shared/nested.rb, line 71
def find_path(val)
  self.each_with_index do |v, k|
    k, v = v if self.kind_of?(Hash)
    return [k] if v == val

    c = v.respond_to?(:find_path) ? v.find_path(val) : []
    return c.unshift(k) unless c.blank?
  end
  []
end
has_key_path?(*args) click to toggle source
# File lib/more_core_extensions/core_ext/shared/nested.rb, line 33
def has_key_path?(*args)
  args = args.first if args.length == 1 && args.first.kind_of?(Array)
  raise ArgumentError, "must pass at least one key" if args.empty?

  key = args.first
  raise ArgumentError, "must be a number" if self.kind_of?(Array) && !key.kind_of?(Numeric)

  has_child = self.kind_of?(Array) ? self.includes_index?(key) : self.has_key?(key)
  return has_child if args.length == 1

  child = self[key]
  return false unless child.respond_to?(:has_key_path?)
  return child.has_key_path?(args[1..-1])
end
Also aliased as: include_path?, key_path?, member_path?
include_path?(*args)
Alias for: has_key_path?
key_path?(*args)
Alias for: has_key_path?
member_path?(*args)
Alias for: has_key_path?
store_path(*args) click to toggle source
# File lib/more_core_extensions/core_ext/shared/nested.rb, line 51
def store_path(*args)
  raise ArgumentError, "must pass at least one key, and a value" if args.length < 2
  value = args.pop
  args = args.first if args.length == 1 && args.first.kind_of?(Array)

  key = args.first
  raise ArgumentError, "must be a number" if self.kind_of?(Array) && !key.kind_of?(Numeric)

  if args.length == 1
    self[key] = value
  else
    child = self[key]
    unless child.respond_to?(:store_path)
      self[key] = self.class.new
      child = self[key]
    end
    child.store_path(args[1..-1].push, value)
  end
end