Permalink
Browse files

Renamed method and handle arrays

  • Loading branch information...
1 parent 2d2b921 commit 01a5165bee5c8cf199e37b3ccc90f1f824d41783 @flori committed Oct 2, 2012
Showing with 17 additions and 10 deletions.
  1. +11 −8 lib/json/generic_object.rb
  2. +6 −2 tests/test_json_generic_object.rb
View
@@ -11,16 +11,19 @@ def json_create(data)
self[data]
end
- def from_hashes(hash)
- result = new
- hash.to_hash.each do |key, value|
- if value.respond_to?(:to_hash)
- result[key] = from_hashes(value)
- else
- result[key] = value
+ def from_hash(object)
+ case
+ when object.respond_to?(:to_hash)
+ result = new
+ object.to_hash.each do |key, value|
+ result[key] = from_hash(value)
end
+ result
+ when object.respond_to?(:to_ary)
+ object.to_ary.map { |a| from_hash(a) }
+ else
+ object
end
- result
end
end
@@ -33,10 +33,14 @@ def test_parse_json
assert_equal 2, l.a.b
end
- def test_from_hashes
- result = GenericObject.from_hashes(:foo => { :bar => { :baz => true } })
+ def test_from_hash
+ result = GenericObject.from_hash(
+ :foo => { :bar => { :baz => true }, :quux => [ { :foobar => true } ] })
assert_kind_of GenericObject, result.foo
assert_kind_of GenericObject, result.foo.bar
assert_equal true, result.foo.bar.baz
+ assert_kind_of GenericObject, result.foo.quux.first
+ assert_equal true, result.foo.quux.first.foobar
+ assert_equal true, GenericObject.from_hash(true)
end
end

0 comments on commit 01a5165

Please sign in to comment.