Skip to content

Commit

Permalink
Restore #from_hash lonely collections support
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Coles <[email protected]>
  • Loading branch information
myabc committed Nov 16, 2016
1 parent cd921d3 commit 8239003
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
8 changes: 8 additions & 0 deletions lib/representable/hash/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ def items(options={}, &block)

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

def from_hash(data, options={}, binding_builder=Binding)
data = filter_wrap(data, options)
data = [data] if ::Hash === data
raise TypeError, "Expected Enumerable, got #{data.class}." unless data.respond_to?(:each)

update_properties_from(data, options, binding_builder)
end

def create_representation_with(doc, options, format)
options = normalize_options(options)
options[:_self] = options
Expand Down
36 changes: 34 additions & 2 deletions test/for_collection_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,38 @@ module SongRepresenter
it { parse(representer.for_collection.new([]), input).must_equal songs }
end
end

# with module including module
end

describe 'bad collections' do
let(:representer) {
Class.new(Representable::Decorator) do
include Representable::Hash
property :name

collection_representer class: Song
end
}

it 'parses when argument is an Array' do
representer.for_collection.new([]).from_hash([{ 'name' => 'Gateways' }])
.must_equal [Song.new('Gateways')]
end

it 'parses when argument is a Hash' do
representer.for_collection.new([]).from_hash('name' => 'Mother North')
.must_equal [Song.new('Mother North')]
end

it 'raises a TypeError when argument is not an Enumerable' do
from_hash = -> {
representer.for_collection.new([]).from_hash(nil)
}.must_raise TypeError
from_hash.message.must_equal 'Expected Enumerable, got NilClass.'

from_hash = -> {
representer.for_collection.new([]).from_hash('')
}.must_raise TypeError
from_hash.message.must_equal 'Expected Enumerable, got String.'
end
end
end

0 comments on commit 8239003

Please sign in to comment.