deltacloud-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mfoj...@redhat.com
Subject [PATCH core 13/16] Core: Fixed 'gsub_keys' helper in Hash to work with Ruby 1.9
Date Thu, 19 Jul 2012 13:02:46 GMT
From: Michal Fojtik <mfojtik@redhat.com>


Signed-off-by: Michal fojtik <mfojtik@redhat.com>
---
 server/lib/deltacloud/core_ext/hash.rb     |   12 +++++++-----
 server/tests/helpers/core_ext/hash_test.rb |   29 +++++++++++++++++++++++-----
 2 files changed, 31 insertions(+), 10 deletions(-)

diff --git a/server/lib/deltacloud/core_ext/hash.rb b/server/lib/deltacloud/core_ext/hash.rb
index fb12045..52c6e89 100644
--- a/server/lib/deltacloud/core_ext/hash.rb
+++ b/server/lib/deltacloud/core_ext/hash.rb
@@ -16,15 +16,17 @@
 class Hash
   def gsub_keys(rgx_pattern, replacement)
     remove = []
-    self.each_key do |key|
+    new_hash = {}
+    each_key do |key|
       if key.to_s.match(rgx_pattern)
          new_key = key.to_s.gsub(rgx_pattern, replacement).downcase
-         self[new_key] = self[key]
-         remove << key
+         new_hash[new_key] = self[key]
+      else
+        new_hash[key] = self[key]
       end
     end
-    #remove the original keys
-    self.delete_if{|k,v| remove.include?(k)}
+    clear
+    merge!(new_hash)
   end
 
   # Method copied from https://github.com/rails/rails/blob/77efc20a54708ba37ba679ffe90021bf8a8d3a8a/activesupport/lib/active_support/core_ext/hash/keys.rb#L23
diff --git a/server/tests/helpers/core_ext/hash_test.rb b/server/tests/helpers/core_ext/hash_test.rb
index 196d70c..5eccdeb 100644
--- a/server/tests/helpers/core_ext/hash_test.rb
+++ b/server/tests/helpers/core_ext/hash_test.rb
@@ -10,12 +10,31 @@ class TestHash < MiniTest::Unit::TestCase
     h = {
       :'test-key-1' => '1',
       :'test-key-2' => '2',
-      :'test-key-3' => '3',
+      'test-key-3' => '3',
+      :random => '10'
     }
-    h.gsub_keys(/test-key/, 'test')
-    assert_equal h['test-1'], '1'
-    assert_equal h['test-2'], '2'
-    assert_equal h['test-3'], '3'
+
+    h.gsub_keys(/test/, 'new')
+
+    assert_equal '1', h['new-key-1']
+    assert_equal '2', h['new-key-2']
+    assert_equal '3', h['new-key-3']
+    assert_equal '10', h[:random]
+  end
+
+  def test_symbolize_keys
+    assert_equal true, {}.respond_to?(:"symbolize_keys")
+    h = {
+      'test1' => 1,
+      :test3 => 3
+    }
+
+    h.symbolize_keys
+
+    assert_equal 1, h[:test1]
+    assert_equal nil, h['test1']
+    assert_equal 3, h[:test3]
+
   end
 
 end
-- 
1.7.10.2


Mime
View raw message