Skip to content

Commit

Permalink
make HAL::Links accept all hyperlink attributes.
Browse files Browse the repository at this point in the history
  • Loading branch information
apotonick committed Mar 16, 2012
1 parent 0d489f3 commit 1c57335
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
7 changes: 5 additions & 2 deletions lib/roar/representer/json/hal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,27 +32,30 @@ def links_definition_options
#
# Note that the HAL::Links module alone doesn't prepend an underscore to +links+. Use the JSON::HAL module for that.
module Links
# TODO: allow more attributes besides :href in Hyperlink.
def self.included(base)
base.class_eval do
include Roar::Representer::Feature::Hypermedia
extend Links::ClassMethods
end
end


module LinkCollectionRepresenter
include JSON

def to_hash(*)
{}.tap do |hash|
each do |link|
hash[link.rel] = {"href" => link.href}
# TODO: we statically use JSON::HyperlinkRepresenter here.
hash[link.rel] = link.extend(JSON::HyperlinkRepresenter).to_hash(:except => [:rel])
end
end
end

def from_hash(json, *)
json.each do |k, v|
self << Feature::Hypermedia::Hyperlink.new(:rel => k, :href => v['href'])
self << Feature::Hypermedia::Hyperlink.new(v.merge :rel => k)
end
self
end
Expand Down
11 changes: 6 additions & 5 deletions test/hal_json_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module SongRepresenter
"http://self"
end

link :next do
link :rel => :next, :title => "Hey, @myabc" do
"http://hit"
end
end
Expand All @@ -19,13 +19,14 @@ module SongRepresenter
@song = Object.new.extend(SongRepresenter)
end

it "renders links plain with the links key" do
assert_equal "{\"links\":{\"self\":{\"href\":\"http://self\"},\"next\":{\"href\":\"http://hit\"}}}", @song.to_json
it "renders links according to the HAL spec" do
assert_equal "{\"links\":{\"self\":{\"href\":\"http://self\"},\"next\":{\"href\":\"http://hit\",\"title\":\"Hey, @myabc\"}}}", @song.to_json
end

it "parses incoming JSON links correctly" do
@song.from_json "{\"links\":{\"self\":{\"href\":\"http://self\"}}}"
assert_equal "http://self", @song.links[:self]
@song.from_json "{\"links\":{\"self\":{\"href\":\"http://self\",\"title\":\"Hey, @myabc\"}}}"
assert_equal "http://self", @song.links[:self].href
assert_equal "Hey, @myabc", @song.links[:self].title
assert_equal nil, @song.links[:next]
end
end
Expand Down

0 comments on commit 1c57335

Please sign in to comment.