Skip to content

Commit 4f8c9e2

Browse files
committed
Restore #from_hash lonely collections support
Signed-off-by: Alex Coles <alex@alexbcoles.com>
1 parent cd921d3 commit 4f8c9e2

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

lib/representable/hash/collection.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ def items(options={}, &block)
1919

2020
# TODO: revise lonely collection and build separate pipeline where we just use Serialize, etc.
2121

22+
def from_hash(data, options={}, binding_builder=Binding)
23+
data = filter_wrap(data, options)
24+
data = [data] if ::Hash === data
25+
raise TypeError, "Expected Enumerable, got #{data.class}." unless data.respond_to?(:each)
26+
27+
update_properties_from(data, options, binding_builder)
28+
end
29+
2230
def create_representation_with(doc, options, format)
2331
options = normalize_options(options)
2432
options[:_self] = options

test/for_collection_test.rb

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,38 @@ module SongRepresenter
6969
it { parse(representer.for_collection.new([]), input).must_equal songs }
7070
end
7171
end
72-
7372
# with module including module
74-
end
73+
74+
describe 'bad collections' do
75+
let(:representer) {
76+
Class.new(Representable::Decorator) do
77+
include Representable::Hash
78+
property :name
79+
80+
collection_representer class: Song
81+
end
82+
}
83+
84+
it 'parses when argument is an Array' do
85+
representer.for_collection.new([]).from_hash([{ 'name' => 'Gateways' }])
86+
.must_equal [Song.new('Gateways')]
87+
end
88+
89+
it 'parses when argument is a Hash' do
90+
representer.for_collection.new([]).from_hash('name' => 'Mother North')
91+
.must_equal [Song.new('Gateways')]
92+
end
93+
94+
it 'raises a TypeError when argument is not an Enumerable' do
95+
from_hash = -> {
96+
representer.for_collection.new([]).from_hash(nil)
97+
}.must_raise TypeError
98+
from_hash.message.must_equal 'Expected Enumerable, got NilClass.'
99+
100+
from_hash = -> {
101+
representer.for_collection.new([]).from_hash('')
102+
}.must_raise TypeError
103+
from_hash.message.must_equal 'Expected Enumerable, got String.'
104+
end
105+
end
106+
end

0 commit comments

Comments
 (0)