Skip to content

Commit b79c2fd

Browse files
committed
Make #from_hash raise TypeError when arg not Hash
Signed-off-by: Alex Coles <alex@alexbcoles.com>
1 parent 7483281 commit b79c2fd

3 files changed

Lines changed: 14 additions & 2 deletions

File tree

lib/representable/hash.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def collection_representer_class
2626

2727
def from_hash(data, options={}, binding_builder=Binding)
2828
data = filter_wrap(data, options)
29+
raise TypeError, "Expected Hash, got #{data.class}." unless ::Hash === data
2930

3031
update_properties_from(data, options, binding_builder)
3132
end

test/hash_test.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ class HashWithScalarPropertyTest < MiniTest::Spec
2727
album.title.must_equal nil
2828
album.extend(representer).from_hash("title" => nil)
2929
end
30+
31+
it 'raises a TypeError when argument is not a Hash' do
32+
from_hash = -> {
33+
album.extend(representer).from_hash('not Hashish')
34+
}.must_raise TypeError
35+
from_hash.message.must_equal 'Expected Hash, got String.'
36+
end
3037
end
3138
end
3239

@@ -157,4 +164,4 @@ class HashWithScalarCollectionTest < MiniTest::Spec
157164
album.extend(representer).from_hash("songs" => ["Off Key Melody", "Sinking"]).must_equal Album.new(["Off Key Melody", "Sinking"])
158165
end
159166
end
160-
end
167+
end

test/wrap_test.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ class BandDecorator < Representable::Decorator
8080
band.from_hash({band: {"name"=>"Social Distortion"}}, wrap: :band).name.must_equal "Social Distortion"
8181
end
8282

83+
it 'raises a TypeError when unwrapped argument is not a Hash' do
84+
-> { band.from_hash('bands' => '') }.must_raise TypeError
85+
-> { band.from_hash('', wrap: false) }.must_raise TypeError
86+
-> { band.from_hash({'band' => ''}, wrap: :band) }.must_raise TypeError
87+
end
8388

8489
class AlbumDecorator < Representable::Decorator
8590
include Representable::Hash
@@ -149,4 +154,3 @@ class AlbumDecorator < Representable::Decorator
149154
# album.from_hash({"albums" => {"band" => {"name"=>"Rvivr"}}}).band.name.must_equal "Rvivr"
150155
# end
151156
end
152-

0 commit comments

Comments
 (0)