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
-
.autovivify(hash, key) ⇒ Object
Create and return a Hash that will auto-vivify any values it is missing with another auto-vivifying Hash.
-
.deep_copy(obj) ⇒ Object
Recursively copy the specified
objand return the result. -
.stringify_keys(hash) ⇒ Object
Return a version of the given
hashwith its keys transformed into Strings from whatever they were before. -
.symbolify_keys(hash) ⇒ Object
(also: internify_keys)
Return a duplicate of the given
hashwith its identifier-like keys transformed into symbols from whatever they were before.
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.
155 156 157 |
# File 'lib/chione/mixins.rb', line 155 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.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/chione/mixins.rb', line 126 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.
162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/chione/mixins.rb', line 162 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.
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/chione/mixins.rb', line 179 def symbolify_keys( hash ) newhash = {} hash.each do |key,val| keysym = key.to_s.dup.to_sym if val.is_a?( Hash ) newhash[ keysym ] = symbolify_keys( val ) else newhash[ keysym ] = val end end return newhash end |