Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/selfbootstrap.rb

Instance Method Summary collapse

Instance Method Details

#deep_merge(second) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/selfbootstrap.rb', line 34

def deep_merge(second)
  merger = proc do |key, v1, v2|
    if v1.is_a?(Hash) && v2.is_a?(Hash)
      v1.deep_merge(v2)
    elsif v1.is_a?(Array) && v2.is_a?(Array)
      v1 | v2
    elsif [:undefined, nil, :nil].include?(v2)
      v1
    else
      v2
    end
  end
  if second.nil?
    self
  else
    merge(second, &merger)
  end
end

#depth_nil?(*names) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
86
87
88
# File 'lib/selfbootstrap.rb', line 83

def depth_nil?(*names)
  return false if names.empty?
  return true if self[names.pop].nil?

  depth_nil?(names)
end

#hashify ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/selfbootstrap.rb', line 94

def hashify
  hash = {}
  excluded_ivars = ivars_excluded_from_hashify

  # Iterate over all the instance variables and store their
  # names and values in a hash
  each do |key, value|
    next if excluded_ivars.include? key.to_s
    value = value.map(&:hashify) if value.is_a? Array
    value = value.hashify if value.is_a? Hash

    hash[key.to_s] = value.to_s
  end
end

#ivars_excluded_from_hashify ⇒ Object



90
91
92
# File 'lib/selfbootstrap.rb', line 90

def ivars_excluded_from_hashify
  @ivars_excluded_from_hash ||= []
end

#stringify_keys(otherhash) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/selfbootstrap.rb', line 57

def stringify_keys(otherhash)
  if otherhash.is_a? Hash
    otherhash.map do |k, v|
      new_v = v.is_a?(Hash) ? stringify_keys(v) : v
      [k.to_s, new_v]
    end.to_h
  else
    otherhash
  end
end

#stringify_keys! ⇒ Object



53
54
55
# File 'lib/selfbootstrap.rb', line 53

def stringify_keys!
  stringify_keys(self)
end

#symbolify_keys(otherhash) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/selfbootstrap.rb', line 72

def symbolify_keys(otherhash)
  if otherhash.is_a? Hash
    otherhash.map do |k, v|
      new_v = v.is_a?(Hash) ? symbolify_keys(v) : v
      [k.to_sym, new_v]
    end.to_h
  else
    otherhash
  end
end

#symbolify_keys! ⇒ Object



68
69
70
# File 'lib/selfbootstrap.rb', line 68

def symbolify_keys!
  symbolify_keys(self)
end

#yaml_output ⇒ Object



109
110
111
112
113
114
115
116
117
# File 'lib/selfbootstrap.rb', line 109

def yaml_output
  yaml_convert = ''
  to_yaml.each_line do |line|
    unless line.include? '---'
      yaml_convert += line
    end
  end
  yaml_convert
end