require 'helper' class Testobject include InstanceVariableHash def initialize(hsh={}) hsh.each{ |key,val| self["@#{key}"] = val } end # shortcuts for testing alias :get :instance_variables_get_as_hash alias :set :instance_variables_set_with_hash alias :[] :instance_variable_get alias :[]= :instance_variable_set end class TestInstanceVarHash < Test::Unit::TestCase context "when getting" do context "vars without underscores" do setup do @obj = Testobject.new :a => 'res_a', :b => 'res_b' end should "have several" do assert_equal 'res_a', @obj.get('a') assert_equal 'res_b', @obj.get('b') assert_equal 'res_b', @obj.get(:b) end end context "vars with one underscore" do setup do @obj = Testobject.new :a_b => 'res_a_b', :a_c => 'res_a_c', :b_c => 'res_b_c', :b_d => 'res_b_d' end should "have several grouped" do res1 = {'b' => 'res_a_b', 'c' => 'res_a_c'} assert_equal res1, @obj.get('a') res2 = {'c' => 'res_b_c', 'd' => 'res_b_d'} assert_equal res2, @obj.get('b') assert_equal res2, @obj.get(:b) end end context "vars with n underscores" do setup do @obj = Testobject.new :a_c_b => 'res_a_c_b', :a_c_d => 'res_a_c_d', :b_c_d => 'res_b_c_d', :b_d_e_f => 'res_b_d_e_f' end should "have several recursively grouped" do res1 = {'c' => {'d' => 'res_a_c_d', 'b' => 'res_a_c_b' }} assert_equal res1, @obj.get('a') res2 = {'c' => {'d' => 'res_b_c_d'}, 'd' => {'e' => { 'f' => 'res_b_d_e_f' }}} assert_equal res2, @obj.get('b') assert_equal res2, @obj.get(:b) end end end context "when setting" do setup do @obj = Testobject.new end should "handle a depth of 1" do @obj.set :a => 'res_a', :b => 'res_b' assert_equal 'res_a', @obj["@a"] assert_equal 'res_b', @obj["@b"] end should "handle a depth of 2" do @obj.set :a => { 'b' => 'res_a_b', :c => 'res_a_c'} assert_equal 'res_a_b', @obj["@a_b"] assert_equal 'res_a_c', @obj["@a_c"] end should "handle a depth of n" do @obj.set :a => { :c => {:d => 'res_a_c_d', :e => { :f => { :g => 'res_a_c_e_f_g' } }}} assert_equal 'res_a_c_e_f_g', @obj["@a_c_e_f_g"] assert_equal 'res_a_c_d', @obj["@a_c_d"] end end end