Skip to content

Commit

Permalink
Merge pull request #60 from abargnesi/hal_link_object_array_issue_58
Browse files Browse the repository at this point in the history
HAL support for an array of linked objects

Dealing with Travis later on, as it's failing for causes unrelated to this PR.
  • Loading branch information
ismasan committed Feb 7, 2015
2 parents c9d76dd + 434b4a5 commit 32990b4
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/oat/adapters/hal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions spec/adapters/hal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
19 changes: 19 additions & 0 deletions spec/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 32990b4

Please sign in to comment.