diff --git a/lib/oat/adapters/hal.rb b/lib/oat/adapters/hal.rb index 20b56c6..ebebc53 100644 --- a/lib/oat/adapters/hal.rb +++ b/lib/oat/adapters/hal.rb @@ -3,7 +3,11 @@ module Oat module Adapters class HAL < Oat::Adapter def link(rel, opts = {}) - data[:_links][rel] = opts if opts[:href] + if opts.is_a?(Array) + data[:_links][rel] = opts.select { |link_obj| link_obj.include?(:href) } + else + data[:_links][rel] = opts if opts[:href] + end end def properties(&block) diff --git a/spec/adapters/hal_spec.rb b/spec/adapters/hal_spec.rb index a0b2107..94df8ac 100644 --- a/spec/adapters/hal_spec.rb +++ b/spec/adapters/hal_spec.rb @@ -81,5 +81,23 @@ ) end end + + let(:array_of_linked_objects_serializer) { + array_of_linked_objects_serializer_class.new(friendly_user, nil, Oat::Adapters::HAL) + } + let(:linked_objects_hash) { array_of_linked_objects_serializer.to_hash } + + context 'with an array of linked objects' do + it 'produces a HAL-compliant hash' do + expect(linked_objects_hash.fetch(:_links).fetch(:related).size).to be 3 + expect(linked_objects_hash.fetch(:_links)).to include( + :related => [ + {:type=>"friend", :href=>"http://foo.bar.com/1"}, + {:type=>"friend", :href=>"http://foo.bar.com/2"}, + {:type=>"friend", :href=>"http://foo.bar.com/3"} + ] + ) + end + end end end diff --git a/spec/fixtures.rb b/spec/fixtures.rb index b435e6b..5c7de1b 100644 --- a/spec/fixtures.rb +++ b/spec/fixtures.rb @@ -5,6 +5,7 @@ def self.included(base) base.let(:friend) { user_class.new('Joe', 33, 2, []) } base.let(:manager) { user_class.new('Jane', 29, 3, []) } base.let(:user) { user_class.new('Ismael', 35, 1, [friend], manager) } + base.let(:friendly_user) { user_class.new('Jeff', 33, 1, [friend, manager, user]) } base.let(:serializer_class) do Class.new(Oat::Serializer) do klass = self @@ -50,6 +51,24 @@ def self.included(base) end end + def url_for(id) + "http://foo.bar.com/#{id}" + end + end + end + base.let(:array_of_linked_objects_serializer_class) do + Class.new(Oat::Serializer) do + schema do + type 'user' + + link :self, :href => url_for(item.id) + link :related, item.friends.map { |friend| + {:type => 'friend', :href => url_for(friend.id)} + }.sort_by { |link_obj| + link_obj[:href] + } + end + def url_for(id) "http://foo.bar.com/#{id}" end