From ae9118461bdd30df1475cd0c1f4ff3e55a91611a Mon Sep 17 00:00:00 2001 From: Roger Campos Date: Fri, 18 Feb 2011 08:56:46 +0100 Subject: [PATCH] .add method refactored and some more specs --- lib/lazyhash.rb | 11 +++-------- spec/lazyhash_spec.rb | 7 +++---- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/lib/lazyhash.rb b/lib/lazyhash.rb index e521e04..b35f5ca 100644 --- a/lib/lazyhash.rb +++ b/lib/lazyhash.rb @@ -1,17 +1,12 @@ module LazyHash class << self - def add(hash, key, value, pre = nil) + def add(hash, key, value) skeys = key.split(".") f = skeys.shift if skeys.empty? - if pre.nil? - hash.send("[]=", f, value) unless hash.has_key?(f) - else - pre.send("[]=", f, value) unless pre.has_key?(f) - end + hash.send("[]=", f, value) unless !hash.is_a?(Hash) || (hash.has_key?(f) && hash[f].is_a?(Hash)) else - pre = pre.nil? ? hash.send("[]", f) : pre.send("[]", f) - add(hash, skeys.join("."), value, pre) + add(hash[f], skeys.join("."), value) end end diff --git a/spec/lazyhash_spec.rb b/spec/lazyhash_spec.rb index 171d16b..dd78b61 100644 --- a/spec/lazyhash_spec.rb +++ b/spec/lazyhash_spec.rb @@ -28,11 +28,10 @@ end it "should not overwrite a node previously defined as a 'value'" do - LazyHash.add(@hash, "es.projects", "title") - LazyHash.add(@hash, "es.projects.title", "Main title") + LazyHash.add(@hash, "es.projects", "Proyectos") + LazyHash.add(@hash, "es.projects.title", "try to convert a value into a folder with other values") - puts @hash.inspect - @hash.should == {"es" => {"projects" => "title"}} + @hash.should == {"es" => {"projects" => "Proyectos"}} end end