From 3d357730f9fa9605df3f75eb0c7a88a0fb68f541 Mon Sep 17 00:00:00 2001 From: Brian Abreu Date: Wed, 24 Jun 2009 10:51:20 -0700 Subject: [PATCH] Fixed ActiveSupport::OrderedHash::[] work identically to ::Hash::[] in ruby 1.8.7 --- activesupport/lib/active_support/ordered_hash.rb | 22 +++++++++++++++--- activesupport/test/ordered_hash_test.rb | 25 +++++++++++++++++++++- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 8d1c0f5..4324e40 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -12,11 +12,25 @@ module ActiveSupport def self.[](*args) ordered_hash = new - args.each_with_index { |val,ind| - # Only every second value is a key. - next if ind % 2 != 0 + + if (args.length == 1 && args.first.is_a?(Array)) + args.first.each do |key_value_pair| + next unless (key_value_pair.is_a?(Array)) + ordered_hash[key_value_pair[0]] = key_value_pair[1] + end + + return ordered_hash + end + + unless (args.size % 2 == 0) + raise ArgumentError.new("odd number of arguments for Hash") + end + + args.each_with_index do |val, ind| + next if (ind % 2 != 0) ordered_hash[val] = args[ind + 1] - } + end + ordered_hash end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index 647938d..15bd571 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -163,9 +163,32 @@ class OrderedHashTest < Test::Unit::TestCase assert @ordered_hash.inspect.include?(@hash.inspect) end - def test_alternate_initialization + def test_alternate_initialization_with_splat alternate = ActiveSupport::OrderedHash[1,2,3,4] assert_kind_of ActiveSupport::OrderedHash, alternate assert_equal [1, 3], alternate.keys end + + def test_alternate_initialization_with_array + alternate = ActiveSupport::OrderedHash[ [ + [1, 2], + [3, 4], + "bad key value pair", + [ 'missing value' ] + ]] + + assert_kind_of ActiveSupport::OrderedHash, alternate + assert_equal [1, 3, 'missing value'], alternate.keys + assert_equal [2, 4, nil ], alternate.values + end + + def test_alternate_initialization_raises_exception_on_odd_length_args + begin + alternate = ActiveSupport::OrderedHash[1,2,3,4,5] + flunk "Hash::[] should have raised an exception on initialization " + + "with an odd number of parameters" + rescue + assert_equal "odd number of arguments for Hash", $!.message + end + end end -- 1.6.1.2