Module: Chione::DataUtilities

Defined in:
lib/chione/mixins.rb

Overview

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

include Chione::DataUtilities
newhash = deep_copy( oldhash )

Class Method Summary collapse

Class Method Details

.autovivify(hash, key) ⇒ Object

Create and return a Hash that will auto-vivify any values it is missing with another auto-vivifying Hash.



156
157
158
# File 'lib/chione/mixins.rb', line 156

def autovivify( hash, key )
	hash[ key ] = Hash.new( &Chione::DataUtilities.method(:autovivify) )
end

.deep_copy(obj) ⇒ Object

Recursively copy the specified obj and return the result.



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/chione/mixins.rb', line 127

def deep_copy( obj )

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

	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
end

.stringify_keys(hash) ⇒ Object

Return a version of the given hash with its keys transformed into Strings from whatever they were before.



163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/chione/mixins.rb', line 163

def stringify_keys( hash )
	newhash = {}

	hash.each do |key,val|
		if val.is_a?( Hash )
			newhash[ key.to_s ] = stringify_keys( val )
		else
			newhash[ key.to_s ] = val
		end
	end

	return newhash
end

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

Return a duplicate of the given hash with its identifier-like keys transformed into symbols from whatever they were before.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/chione/mixins.rb', line 180

def symbolify_keys( hash )
	newhash = {}

	hash.each do |key,val|
		keysym = key.to_s.dup.untaint.to_sym

		if val.is_a?( Hash )
			newhash[ keysym ] = symbolify_keys( val )
		else
			newhash[ keysym ] = val
		end
	end

	return newhash
end