Module: Mixins::DataUtilities

Defined in:
lib/mixins/data_utilities.rb

Overview

A collection of miscellaneous functions that are useful for manipulating complex data structures.

include Mixins::DataUtilities
newhash = deep_copy( oldhash )

# or called as a module function
newhash = Mixins::DataUtilities.deep_copy( oldhash )

Class Method Summary collapse

Class Method Details

.deep_copy(obj) ⇒ Object

Recursively copy the specified obj and return the result.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mixins/data_utilities.rb', line 25

def deep_copy( obj )

	# Handle mocks during testing
	return obj if obj.class.name == 'RSpec::Mocks::Mock'

	# rubocop:disable Layout/IndentationWidth, Layout/IndentationStyle
	return case obj
		when NilClass, Numeric, TrueClass, FalseClass, Symbol,
		     Module, Encoding, IO, Tempfile
			obj

		when Array
			obj.map {|o| deep_copy(o) }

		when Hash
			newhash = {}
			newhash.default_proc = obj.default_proc if obj.default_proc
			obj.each do |k,v|
				newhash[ deep_copy(k) ] = deep_copy( v )
			end
			newhash

		else
			obj.clone
		end
		# rubocop:enable Layout/IndentationWidth, Layout/IndentationStyle
end

.stringify_keys(object) ⇒ Object

Return a duplicate of the given object with its Symbol keys transformed into Strings.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mixins/data_utilities.rb', line 56

def stringify_keys( object )
	case object
	when Hash
		return object.each_with_object( {} ) do |(key,val), newhash|
			key = key.to_s if key.is_a?( Symbol )
			newhash[ key ] = stringify_keys( val )
		end
	when Array
		return object.map {|el| stringify_keys(el) }
	else
		return object
	end
end

.symbolify_keys(object) ⇒ Object Also known as: internify_keys

Return a duplicate of the given object with its identifier-like String keys transformed into Symbols.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/mixins/data_utilities.rb', line 73

def symbolify_keys( object )
	case object
	when Hash
		return object.each_with_object( {} ) do |(key,val), newhash|
			key = key.to_sym if key.respond_to?( :to_sym ) &&
				key.match?( /\A\w+\Z/ )
			newhash[ key ] = symbolify_keys( val )
		end
	when Array
		return object.map {|el| symbolify_keys(el) }
	else
		return object
	end
end