# 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 # 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