module JamfRubyExtensions::Hash::Utils

Public Instance Methods

j_nillify!(to_nils = '', recurse = false) { |v| ... } click to toggle source

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.

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

@param recurse should sub-Hashes be nillified?

@yield [value] Hash values for which the block returns true will become nil.

@return [Hash] the hash with the desired values converted to nil

@example

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 }}
    # File lib/jamf/ruby_extensions/hash/utils.rb
 87 def j_nillify!(to_nils = '', recurse = false, &block)
 88   nillify_these = [] << to_nils
 89   nillify_these.flatten!
 90 
 91   each_pair do |k, v|
 92     if v.instance_of?(Hash)
 93       v.jss_nillify!(to_nils, recurse, &block)
 94       next
 95     end
 96     do_it =
 97       if block_given?
 98         yield v
 99       else
100         nillify_these.include? v
101       end
102     self[k] = nil if do_it
103   end # each pair
104 end
Also aliased as: jss_nillify!
jss_nillify!(to_nils = '', recurse = false, &block)
Alias for: j_nillify!