Class: Hash

Inherits:
Object show all
Defined in:
lib/vagrant-invade/extend.rb

Instance Method Summary collapse

Instance Method Details

#compactObject



26
27
28
# File 'lib/vagrant-invade/extend.rb', line 26

def compact
  self.select { |_, value| !value.nil? }
end

#compact!Object



30
31
32
# File 'lib/vagrant-invade/extend.rb', line 30

def compact!
  self.reject! { |_, value| value.nil? }
end

#deep_compact(options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/vagrant-invade/extend.rb', line 34

def deep_compact(options = {})
  inject({}) do |new_hash, (k,v)|
    result = options[:exclude_blank] ? v.blank? : v.nil?
    if !result
      new_value = v.is_a?(Hash) ? v.deep_compact(options).presence : v
      new_hash[k] = new_value if new_value
    end
    new_hash
  end
end

#deep_merge(other_hash, &block) ⇒ Object



45
46
47
# File 'lib/vagrant-invade/extend.rb', line 45

def deep_merge(other_hash, &block)
  dup.deep_merge!(other_hash, &block)
end

#deep_merge!(other_hash, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/vagrant-invade/extend.rb', line 49

def deep_merge!(other_hash, &block)
  other_hash.each_pair do |current_key, other_value|
    this_value = self[current_key]

    self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash)
      this_value.deep_merge(other_value, &block)
    else
      if block_given? && key?(current_key)
        block.call(current_key, this_value, other_value)
      else
        other_value
      end
    end
  end

  self
end

#depthObject



17
18
19
20
21
22
23
24
# File 'lib/vagrant-invade/extend.rb', line 17

def depth
    a = self.to_a
    d = 1
    while (a.flatten!(1).map! {|e| (e.is_a? Hash) ? e.to_a.flatten(1) : (e.is_a? Array) ? e : nil}.compact!.size > 0)
        d += 1
    end
    d
end