Sha256: 30a4b8799aa8191a9b1eb4ae879c4d83b9bd2a07b4015fbc1b59ea8b03d8fbca
Contents?: true
Size: 1.65 KB
Versions: 1
Compression:
Stored size: 1.65 KB
Contents
# Author:: Marc Rene Arns (Base64.decode64('bGludXhAbWFyY3JlbmVhcm5zLmRl\n')) # Copyright:: Copyright (c) 2011 Marc Rene Arns # License:: Distributes under the same terms as Ruby # This module has two methods to convert between @under_scored_instance_variables # and recursive Hashes, see README and the unit tests for examples module InstanceVariableHash # get all instance variables that begin with 'key' as a recursive Hash (separated by _) def instance_variables_get_as_hash(key) response = {} # we need a hash to have an object (id) to attach to self.instance_variables.each do |var| if var =~ /^@#{Regexp.escape(key.to_s)}(.*)$/ # we take the exact match and the subkeys keys, hsh, pre = $1.split('_'), response, [] keys[0] = key # put the key itself into the result to have it in the loop stop = keys.size keys.each do |k| pre << k if pre.size == stop # last element hsh[k] = self.instance_variable_get("@#{pre.join('_')}") else hsh[k] ||= {} hsh = hsh[k] end end end end return response[key] end def ivars_to_hash(key) instance_variables_get_as_hash(key) end def ivars_from_hash(hsh) instance_variables_set_with_hash(hsh) end # set instance variables by a Hash, so that they will end up with underscored names def instance_variables_set_with_hash(hsh) meth = proc do |pre,h| h.each do |k,v| keys = (pre.dup << k) v.is_a?(Hash) ? meth.call(keys,v) : self.instance_variable_set("@#{keys.join('_')}", v) end end meth.call [], hsh end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
instance_variable_hash-1.1.0 | lib/instance_variable_hash.rb |