Sha256: f70f9dc12a505f5c68d07e8d93aeee0a09f6b7e8b2f70d3bdbe96f50770ed23e

Contents?: true

Size: 881 Bytes

Versions: 2

Compression:

Stored size: 881 Bytes

Contents

class Hash
  # Merges defaults with the hash
  def with_defaults(defaults)
    self.merge(defaults) { |key,old,new| old.nil? ? new : old }
  end

  # Merges defaults with the hash (destructive)
  def with_defaults!(defaults)
    self.merge!(defaults) { |key,old,new| old.nil? ? new : old }
  end

  def nested_find(*keys)
    v = self
    keys.each do |key|
      v = v[key]
      return nil if v.nil?
    end
    return v
  end

  # http://snippets.dzone.com/posts/show/4146
  def deep_merge!(second)
    # From: http://www.ruby-forum.com/topic/142809
    # Author: Stefan Rusterholz
    merger = proc { |key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
    self.merge!(second, &merger)
  end

  def method_missing(m,*a)
    if m.to_s =~ /=$/
      self[$`] = a[0]
    elsif a.empty?
      self[m]
    else
      raise NoMethodError, "#{ m}"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
darkhelmet-darkext-0.11.1 lib/darkext/hash.rb
darkhelmet-darkext-0.11.2 lib/darkext/hash.rb