Module: JamfRubyExtensions::Hash::Utils

Included in:
Hash
Defined in:
lib/jamf/ruby_extensions/hash/utils.rb

Instance Method Summary collapse

Instance Method Details

#j_nillify!(to_nils = '', recurse = false) {|value| ... } ⇒ Hash Also known as: jss_nillify!

Convert Hash values to nil. This is useful in the Classic API due to lack of consistency as to whether unset values come to us as nils or empty strings. This APIObject class converts all empty strings to nils using this method.

With no block, values equalling the String, or any member of the Array, given will be converted to nil. Equality is evaluated with == and Array#include?

With a block, if the result of the block evaluates to true, the value is converted to nil.

Subhashes are ignored unless recurse is true.

Examples:

hash = {:foo => '', :bar => {:baz => '' }}
hash.jss_nillify!  # {:foo => nil, :bar => {:baz => '' }}

hash = {:foo => '', :bar => {:baz => '' }}
hash.jss_nillify! '', :recurse  # {:foo => nil, :bar => {:baz => nil }}

hash = {:foo => 123, :bar => {:baz => '', :bim => "123" }}
hash.jss_nillify! ['', 123], :recurse # {:foo => nil, :bar => {:baz => nil, :bim => "123" }}

hash = {:foo => 123, :bar => {:baz => '', :bim => "123" }}
hash.jss_nillify!(:anything, :recurse){|v| v.to_i == 123 }  # {:foo => nil, :bar => {:baz => '', :bim => nil }}

Parameters:

  • to_nils (String, Array) (defaults to: '')

    Hash values equal to (==) these become nil. Defaults to empty string

  • recurse (Boolean) (defaults to: false)

    should sub-Hashes be nillified?

Yields:

  • (value)

    Hash values for which the block returns true will become nil.

Returns:

  • (Hash)

    the hash with the desired values converted to nil



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/jamf/ruby_extensions/hash/utils.rb', line 87

def j_nillify!(to_nils = '', recurse = false, &block)
  nillify_these = [] << to_nils
  nillify_these.flatten!

  each_pair do |k, v|
    if v.instance_of?(Hash)
      v.jss_nillify!(to_nils, recurse, &block)
      next
    end
    do_it =
      if block_given?
        yield v
      else
        nillify_these.include? v
      end
    self[k] = nil if do_it
  end # each pair
end