11require 'hyperclient/collection'
22require 'hyperclient/link'
3+ require 'hyperclient/curie'
34
45module Hyperclient
56 # Public: A wrapper class to easily acces the links in a Resource.
@@ -12,13 +13,19 @@ module Hyperclient
1213 class LinkCollection < Collection
1314 # Public: Initializes a LinkCollection.
1415 #
15- # collection - The Hash with the links.
16+ # collection - The Hash with the links.
17+ # curies - Link curies.
1618 # entry_point - The EntryPoint object to inject the configuration.
17- def initialize ( collection , entry_point )
19+ def initialize ( collection , curies , entry_point )
1820 fail "Invalid response for LinkCollection. The response was: #{ collection . inspect } " if collection && !collection . respond_to? ( :collect )
1921
22+ @curies = ( curies || { } ) . reduce ( { } ) do |hash , curie_hash |
23+ curie = build_curie ( curie_hash , entry_point )
24+ hash . update ( curie . name => curie )
25+ end
26+
2027 @collection = ( collection || { } ) . reduce ( { } ) do |hash , ( name , link ) |
21- hash . update ( name => build_link ( name , link , entry_point ) )
28+ hash . update ( name => build_link ( name , link , @curies , entry_point ) )
2229 end
2330 end
2431
@@ -27,16 +34,33 @@ def initialize(collection, entry_point)
2734 # Internal: Creates links from the response hash.
2835 #
2936 # link_or_links - A Hash or an Array of hashes with the links to build.
30- # entry_point - The EntryPoint object to inject the configuration.
37+ # entry_point - The EntryPoint object to inject the configuration.
38+ # curies - Optional curies for templated links.
3139 #
3240 # Returns a Link or an array of Links when given an Array.
33- def build_link ( name , link_or_links , entry_point )
41+ def build_link ( name , link_or_links , curies , entry_point )
3442 return unless link_or_links
35- return Link . new ( name , link_or_links , entry_point ) unless link_or_links . respond_to? ( :to_ary )
36-
37- link_or_links . map do |link |
38- build_link ( name , link , entry_point )
43+ if link_or_links . respond_to? ( :to_ary )
44+ link_or_links . map do |link |
45+ build_link ( name , link , curies , entry_point )
46+ end
47+ elsif ( curie_parts = /(?<ns>[^:]+):(?<short_name>.+)/ . match ( name ) )
48+ curie = curies [ curie_parts [ :ns ] ]
49+ link_or_links [ 'href' ] = curie . expand ( link_or_links [ 'href' ] ) if curie
50+ Link . new ( name , link_or_links , entry_point )
51+ else
52+ Link . new ( name , link_or_links , entry_point )
3953 end
4054 end
55+
56+ # Internal: Creates a curie from the response hash.
57+ #
58+ # curie_hash - A Hash with the curie.
59+ # entry_point - The EntryPoint object to inject the configuration.
60+ #
61+ # Returns a Link or an array of Links when given an Array.
62+ def build_curie ( curie_hash , entry_point )
63+ Curie . new ( curie_hash , entry_point )
64+ end
4165 end
4266end
0 commit comments