require File.dirname(__FILE__) + '/../lib/hash_magic' describe Hash do it "#slashed should return an equivalent SlashedHash object" do sl = {'a' => 'b', 'c' => {'d' => 'e'}}.slashed sl.class.should be(SlashedHash) (sl.keys - ['a', 'c']).should eql([]) end it "#ordered should return an equivalent OrderedHash object" do sl = {'a' => 'b', 'c' => {'d' => 'e'}}.ordered('c', 'a') sl.class.should be(OrderedHash) sl.keys.should eql(['c','a']) end end describe "SlashedHash#initialize" do it "should initialize from a hash input" do sl = SlashedHash.new({'a' => 'b', 'c' => {'d' => 'e'}}) (sl.keys - ['a', 'c']).should eql([]) end end describe SlashedHash do before do @slash = {'a' => 'b', 'c' => {'d' => 'e'}}.slashed end it "should respond to every core Hash method properly" do @slash.should be_respond_to(:[]) @slash.should be_respond_to(:keys) @slash.should be_respond_to(:inject) end it "should inspect like a hash, with 'slashed: ' inserted" do @slash.inspect.should eql("{slashed: \"a\"=>\"b\", \"c/d\"=>\"e\"}") end it "should access values by key and by slashed key" do @slash['a'].should eql('b') @slash['c'].should == {'d' => 'e'} @slash['c/d'].should eql('e') end it "should expand properly" do @slash.expand.should == {'a' => 'b', 'c' => {'d' => 'e'}} end it "should dup properly" do @slash.dup.inspect.should eql(@slash.inspect) end it "should set values properly" do @slash['a'] = 'bb' @slash['c/d'] = {'t/h' => 'i'} @slash['c']['d']['t']['h'].should eql('i') @slash['c'].inspect end it "should flatten and expand a complex hash properly" do sl = {'a' => 'b', 'c' => {'d' => 'e', 'e' => {'f' => [1,2,3], 'fe' => :jo}}}.slashed (sl.expand.keys - ['a', 'b', 'c']).should eql([]) (sl['c'].keys - ['d', 'e']).should eql([]) (sl['c/e'].keys - ['f', 'fe']).should eql([]) sl['c']['e/f'].should eql([1,2,3]) sl['c/e']['fe'].should eql(:jo) end end describe OrderedHash do before do @ordered = {'a' => 'b', 'c' => {'d' => 'e'}}.ordered('c', 'a') end it "should respond to every core Hash method" do @ordered.should be_respond_to(:[]) @ordered.should be_respond_to(:keys) @ordered.should be_respond_to(:inject) end it "should perform each_key properly" do ary = [] @ordered.each_key {|k| ary << k} ary.should eql(['c', 'a']) end it "should perform each properly" do ary = [] @ordered.each {|k,v| ary << k} ary.should eql(['c', 'a']) end it "should perform to_a properly" do @ordered.to_a.inspect.should eql([ ['c', {'d' => 'e'}], ['a', 'b'] ].inspect) end it "should perform inject properly" do @ordered.inject([]) {|a,(k,v)| a << k; a}.should eql(@ordered.keys) end it "#slashed should return an equivalent SlashedHash object" do sl = @ordered.slashed sl.class.should be(SlashedHash) sl.keys.should eql(['c','a']) end end