Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HAL support for an array of linked objects #60

Merged
merged 1 commit into from
Feb 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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