Skip to content
This repository has been archived by the owner on Apr 16, 2022. It is now read-only.

Commit

Permalink
Fixed bug around Array#each
Browse files Browse the repository at this point in the history
  • Loading branch information
Tammer Saleh committed Feb 7, 2012
1 parent d5e8121 commit 8799007
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 9 deletions.
9 changes: 9 additions & 0 deletions lib/deep_struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ def self.from_data(data)
end
end

def self.convert_element_if_possible(e)
case e
when ::Array then DeepStruct::Array.new(e)
when ::Hash then DeepStruct::Hash.new(e)
else
e
end
end

def self.from_file(path)
from_data(FileReader.new(path).data)
end
Expand Down
11 changes: 7 additions & 4 deletions lib/deep_struct/array.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
class DeepStruct::Array < Array
def [](index)
v = super
return DeepStruct::Hash.new(v) if v.is_a?(::Hash)
return DeepStruct::Array.new(v) if v.is_a?(::Array)
return v
DeepStruct.convert_element_if_possible(super)
end

# The annoyance of subclassing Array is that ruby implements many array
Expand All @@ -13,4 +10,10 @@ def [](index)
def first
self[0]
end

def each(&block)
self.to_a.each do |e|
DeepStruct.convert_element_if_possible(e)
end
end
end
5 changes: 1 addition & 4 deletions lib/deep_struct/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ def initialize(hash)
end

def [](key)
v = super(key)
return DeepStruct::Hash.new(v) if v.is_a?(::Hash)
return DeepStruct::Array.new(v) if v.is_a?(::Array)
return v
DeepStruct.convert_element_if_possible(super)
end

def method_missing(key, *args, &block)
Expand Down
2 changes: 1 addition & 1 deletion lib/deep_struct/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module DeepStruct
VERSION = "1.0.1"
VERSION = "1.0.2"
end
8 changes: 8 additions & 0 deletions spec/deep_struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
its("first.one") { should == 1 }
its("second.two") { should == 2 }
its("first.unknown") { should == nil }

describe "#each" do
it "returns each element as a DeepStruct::Hash" do
deep_struct.each do |ds_hash|
ds_hash.should be_a(DeepStruct::Hash)
end
end
end
end

context "instance with a hash of arrays of hashes" do
Expand Down

0 comments on commit 8799007

Please sign in to comment.