Module: InstanceVariableHash
- Defined in:
- lib/instance_variable_hash.rb
Overview
This module has two methods to convert between @under_scored_instance_variables and recursive Hashes, see README and the unit tests for examples
Instance Method Summary collapse
-
#instance_variables_get_as_hash(key) ⇒ Object
get all instance variables that begin with ‘key’ as a recursive Hash (separated by _).
-
#instance_variables_set_with_hash(hsh) ⇒ Object
set instance variables by a Hash, so that they will end up with underscored names.
- #ivars_from_hash(hsh) ⇒ Object
- #ivars_to_hash(key) ⇒ Object
Instance Method Details
#instance_variables_get_as_hash(key) ⇒ Object
get all instance variables that begin with ‘key’ as a recursive Hash (separated by _)
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/instance_variable_hash.rb', line 10 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 |
#instance_variables_set_with_hash(hsh) ⇒ Object
set instance variables by a Hash, so that they will end up with underscored names
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/instance_variable_hash.rb', line 40 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 |
#ivars_from_hash(hsh) ⇒ Object
35 36 37 |
# File 'lib/instance_variable_hash.rb', line 35 def ivars_from_hash(hsh) instance_variables_set_with_hash(hsh) end |
#ivars_to_hash(key) ⇒ Object
31 32 33 |
# File 'lib/instance_variable_hash.rb', line 31 def ivars_to_hash(key) instance_variables_get_as_hash(key) end |