Skip to content

Commit

Permalink
Don't create resources with empty representation when resources come …
Browse files Browse the repository at this point in the history
…from links
  • Loading branch information
oriolgual committed Jun 30, 2012
1 parent 560ad7a commit 12a481f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 10 deletions.
28 changes: 18 additions & 10 deletions lib/hyperclient/discoverer.rb
Expand Up @@ -44,7 +44,7 @@ def resources

@resources ||= @representation.inject({}) do |memo, (name, representation)|
next memo if name == 'self'
memo.update(name => build_resource(representation, name))
memo.update(name => build_resource(representation, name))
end
end

Expand All @@ -55,19 +55,27 @@ def resources
def build_resource(representation, name = nil)
return representation.map(&method(:build_resource)) if representation.is_a?(Array)

url = extract_url(representation)
url = URLExtractor.new(representation).url
ResourceFactory.resource(url, {representation: representation, name: name})
end

# Internal: Returns a String with the resource URL
#
# representation - The JSON representation of the resource.
def extract_url(representation)
return representation['href'] if representation.include?('href')
# Internal: Extract the url from a HAL representation.
class URLExtractor
# Public: Initializes a URLExtractor.
#
# representation - A Hash with the representation of a Resource.
def initialize(representation)
@representation = representation
end

# Public: Returns a String with the resource URL
def url
return @representation.delete('href') if @representation.include?('href')

if representation && representation['_links'] && representation['_links']['self'] &&
(url = representation['_links']['self']['href'])
return url
if @representation && @representation['_links'] && @representation['_links']['self'] &&
(url = @representation['_links']['self']['href'])
return url
end
end
end
end
Expand Down
25 changes: 25 additions & 0 deletions test/hyperclient/discoverer_test.rb
Expand Up @@ -72,5 +72,30 @@ module Hyperclient
discoverer.filter.name.wont_be_empty
end
end

describe Discoverer::URLExtractor do
describe 'url' do
it 'extracts the url from embedded resources' do
hal = {'_links' => {'self' => {'href' => '/path/to/resource'}}}
extractor = Discoverer::URLExtractor.new(hal)

extractor.url.must_equal '/path/to/resource'
end

it 'extracts the url from linked resources' do
hal = {'href' => '/path/to/resource'}
extractor = Discoverer::URLExtractor.new(hal)

extractor.url.must_equal '/path/to/resource'
end

it 'deletes the url from linked resources to prevent empty representations' do
hal = {'href' => '/path/to/resource'}
Discoverer::URLExtractor.new(hal).url

hal.include?('href').must_equal false
end
end
end
end
end

0 comments on commit 12a481f

Please sign in to comment.