Sha256: 96919d580aaf9f14508466daccaae300c2007fb1a46575b7e9e62aaf9f338570

Contents?: true

Size: 1.1 KB

Versions: 6

Compression:

Stored size: 1.1 KB

Contents

class Hash
  DEFAULT_SEPERATOR = '/'

  def flatten(seperator = DEFAULT_SEPERATOR, prefix = nil)
    new_hash = {}

    each do |key, value|
      new_key = [prefix, key].compact.join(seperator)
      if value.is_a?(self.class)
        new_hash.update value.flatten(seperator, new_key)
      else
        new_hash.update new_key => value
      end
    end

    new_hash
  end

  def flatten!(*args)
    replace flatten(*args)
  end

  def at(path, seperator = DEFAULT_SEPERATOR)
    current = self
    
    parts = path.split(DEFAULT_SEPERATOR)
    key = parts.pop

    return unless key

    parts.each do |part|
      current = current[part]
      
      return unless current.is_a?(self.class)
    end

    current[key]
  end

  def update_at(path, value, seperator = DEFAULT_SEPERATOR)
    current = self
    
    parts = path.split(DEFAULT_SEPERATOR)
    key = parts.pop

    return self unless key

    parts.each do |part|
      current[part] ||= {}
      current = current[part]
      
      raise 'updating value at %s failed!' % inspect unless current.is_a?(self.class)
    end

    current[key] = value
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rid-0.5.2 lib/rid/core_ext/hash.rb
rid-0.5.1 lib/rid/core_ext/hash.rb
rid-0.5.0 lib/rid/core_ext/hash.rb
rid-0.4.1 lib/rid/core_ext/hash.rb
rid-0.4.0 lib/rid/core_ext/hash.rb
rid-0.3.1 lib/rid/core_ext/hash.rb