roar 0.0.1.alpha1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +2 -0
  3. data/.travis.yml +10 -0
  4. data/CHANGES.markdown +203 -0
  5. data/Gemfile +6 -0
  6. data/LICENSE +20 -0
  7. data/README.markdown +734 -0
  8. data/Rakefile +10 -0
  9. data/TODO.markdown +13 -0
  10. data/examples/example.rb +370 -0
  11. data/examples/example_server.rb +34 -0
  12. data/gemfiles/Gemfile.representable-2.0 +5 -0
  13. data/gemfiles/Gemfile.representable-2.1 +5 -0
  14. data/lib/roar/client.rb +38 -0
  15. data/lib/roar/coercion.rb +20 -0
  16. data/lib/roar/decorator.rb +11 -0
  17. data/lib/roar/http_verbs.rb +88 -0
  18. data/lib/roar/hypermedia.rb +179 -0
  19. data/lib/roar/json/collection.rb +3 -0
  20. data/lib/roar/json/collection_json.rb +208 -0
  21. data/lib/roar/json/hal.rb +223 -0
  22. data/lib/roar/json/hash.rb +3 -0
  23. data/lib/roar/json/json_api.rb +228 -0
  24. data/lib/roar/json.rb +55 -0
  25. data/lib/roar/representer.rb +11 -0
  26. data/lib/roar/transport/faraday.rb +49 -0
  27. data/lib/roar/transport/net_http/request.rb +77 -0
  28. data/lib/roar/transport/net_http.rb +49 -0
  29. data/lib/roar/version.rb +1 -1
  30. data/lib/roar/xml.rb +54 -0
  31. data/lib/roar.rb +4 -1
  32. data/roar.gemspec +14 -5
  33. data/test/client_test.rb +36 -0
  34. data/test/coercion_feature_test.rb +23 -0
  35. data/test/collection_json_test.rb +130 -0
  36. data/test/decorator_test.rb +132 -0
  37. data/test/faraday_http_transport_test.rb +82 -0
  38. data/test/fixtures/sample.pem +31 -0
  39. data/test/hal_json_test.rb +160 -0
  40. data/test/hal_links_test.rb +31 -0
  41. data/test/http_verbs_test.rb +154 -0
  42. data/test/hypermedia_feature_test.rb +155 -0
  43. data/test/hypermedia_test.rb +190 -0
  44. data/test/integration/Gemfile +4 -0
  45. data/test/integration/band_representer.rb +8 -0
  46. data/test/integration/runner.rb +42 -0
  47. data/test/integration/server.rb +120 -0
  48. data/test/integration/ssl_server.rb +60 -0
  49. data/test/json_api_test.rb +395 -0
  50. data/test/json_representer_test.rb +149 -0
  51. data/test/lib/runner.rb +134 -0
  52. data/test/lonely_test.rb +9 -0
  53. data/test/net_http_transport_test.rb +78 -0
  54. data/test/representer_test.rb +39 -0
  55. data/test/ssl_client_certs_test.rb +102 -0
  56. data/test/test_helper.rb +60 -0
  57. data/test/xml_representer_test.rb +68 -0
  58. metadata +209 -49
@@ -0,0 +1,179 @@
1
+ module Roar
2
+ # Define hypermedia links in your representations.
3
+ #
4
+ # Example:
5
+ #
6
+ # class Order
7
+ # include Roar::Representer::JSON
8
+ #
9
+ # property :id
10
+ #
11
+ # link :self do
12
+ # "http://orders/#{id}"
13
+ # end
14
+ #
15
+ # If you want more attributes, just pass a hash to #link.
16
+ #
17
+ # link :rel => :next, :title => "Next, please!" do
18
+ # "http://orders/#{id}"
19
+ # end
20
+ #
21
+ # If you need dynamic attributes, the block can return a hash.
22
+ #
23
+ # link :preview do
24
+ # {:href => image.url, :title => image.name}
25
+ # end
26
+ #
27
+ # Sometimes you need values from outside when the representation links are rendered. Just pass them
28
+ # to the render method, they will be available as block parameters.
29
+ #
30
+ # link :self do |opts|
31
+ # "http://orders/#{opts[:id]}"
32
+ # end
33
+ #
34
+ # model.to_json(:id => 1)
35
+ module Hypermedia
36
+ # links= [Hyperlink, Hyperlink] is where parsing happens.
37
+ def self.included(base)
38
+ base.extend ClassMethods
39
+ end
40
+
41
+ def links=(arr) # called when assigning parsed links.
42
+ @links = LinkCollection[*arr]
43
+ end
44
+
45
+ attr_reader :links # this is only useful after parsing.
46
+
47
+
48
+ module LinkConfigsMethod
49
+ def link_configs # we could store the ::link configs in links Definition.
50
+ representable_attrs[:links] ||= Representable::Inheritable::Array.new
51
+ end
52
+ end
53
+
54
+ include LinkConfigsMethod
55
+
56
+ private
57
+ # Create hypermedia links for this instance by invoking their blocks.
58
+ # This is called in links: getter: {}.
59
+ def prepare_links!(options)
60
+ return [] if options[:links] == false
61
+
62
+ LinkCollection[*compile_links_for(link_configs, options)]
63
+ end
64
+
65
+ def compile_links_for(configs, *args)
66
+ configs.collect do |config|
67
+ options, block = config.first, config.last
68
+ href = run_link_block(block, *args) or next
69
+
70
+ prepare_link_for(href, options)
71
+ end.compact # FIXME: make this less ugly.
72
+ end
73
+
74
+ def prepare_link_for(href, options)
75
+ options = options.merge(href.is_a?(::Hash) ? href : {:href => href})
76
+ Hyperlink.new(options)
77
+ end
78
+
79
+ def run_link_block(block, *args)
80
+ instance_exec(*args, &block)
81
+ end
82
+
83
+
84
+ # LinkCollection keeps an array of Hyperlinks to be rendered (setup in #prepare_links!)
85
+ # or parsed (array is passed to #links= which transforms it into a LinkCollection).
86
+ # It is implemented as a hash and keys links by their rel value.
87
+ #
88
+ # {"self" => <Hyperlink ..>, ..}
89
+ class LinkCollection < ::Hash
90
+ # The only way to create is LinkCollection[<Hyperlink>, <Hyperlink>]
91
+ def self.[](*arr)
92
+ super(arr.collect { |link| [link.rel, link] })
93
+ end
94
+
95
+ def [](rel)
96
+ super(rel.to_s)
97
+ end
98
+
99
+ # Iterating links. Block parameters: |link| or |rel, link|.
100
+ # This is used Hash::HashBinding#serialize.
101
+ def each(&block)
102
+ return values.each(&block) if block.arity == 1
103
+ super(&block)
104
+ end
105
+
106
+ def collect(&block) # TODO: remove me when we drop representable 2.0.x support!
107
+ return values.collect(&block) if block.arity == 1
108
+ super(&block)
109
+ end
110
+ end
111
+
112
+
113
+ module ClassMethods
114
+ # Declares a hypermedia link in the document.
115
+ #
116
+ # Example:
117
+ #
118
+ # link :self do
119
+ # "http://orders/#{id}"
120
+ # end
121
+ #
122
+ # The block is executed in instance context, so you may call properties or other accessors.
123
+ # Note that you're free to put decider logic into #link blocks, too.
124
+ def link(options, &block)
125
+ create_links_definition! # this assures the links are rendered at the right position.
126
+
127
+ options = {:rel => options} unless options.is_a?(::Hash)
128
+ link_configs << [options, block]
129
+ end
130
+
131
+ include LinkConfigsMethod
132
+
133
+ private
134
+ # Add a :links Definition to the representable_attrs so they get rendered/parsed.
135
+ def create_links_definition!
136
+ return if representable_attrs.get(:links) # only create it once.
137
+
138
+ options = links_definition_options
139
+ options.merge!(:getter => lambda { |opts| prepare_links!(opts) })
140
+
141
+ representable_attrs.add(:links, options)
142
+ end
143
+ end
144
+
145
+
146
+ # An abstract hypermedia link with arbitrary attributes.
147
+ class Hyperlink
148
+ extend Forwardable
149
+ def_delegators :@attrs, :each, :collect
150
+
151
+ def initialize(attrs={})
152
+ @attrs = attributes!(attrs)
153
+ end
154
+
155
+ def replace(attrs) # makes it work with Hash::Hash.
156
+ @attrs = attributes!(attrs)
157
+ self
158
+ end
159
+
160
+ # Only way to write to Hyperlink after creation.
161
+ def merge!(attrs)
162
+ @attrs.merge!(attributes!(attrs))
163
+ end
164
+
165
+ private
166
+ def method_missing(name)
167
+ @attrs[name.to_s]
168
+ end
169
+
170
+ # Converts keys to strings.
171
+ def attributes!(attrs)
172
+ attrs.inject({}) { |hsh, kv| hsh[kv.first.to_s] = kv.last; hsh }.tap do |hsh|
173
+ hsh["rel"] = hsh["rel"].to_s if hsh["rel"]
174
+ end
175
+ # raise "Hyperlink without rel doesn't work!" unless @attrs["rel"]
176
+ end
177
+ end
178
+ end
179
+ end
@@ -0,0 +1,3 @@
1
+ require "representable/json/collection"
2
+
3
+ Roar::JSON::Collection = Representable::JSON::Collection
@@ -0,0 +1,208 @@
1
+ module Roar::JSON
2
+ # Implementation of the Collection+JSON media format, http://amundsen.com/media-types/collection/format/
3
+ #
4
+ # When clients want to add or update an item the collection's filled out template is POSTed or PUT. You can parse that using the
5
+ # +SongCollectionRepresenter::template_representer+ module.
6
+ #
7
+ # Song.new.extend(SongCollectionRepresenter.template_representer).from_json("{template: ...")
8
+ module CollectionJSON
9
+ def self.included(base)
10
+ base.class_eval do
11
+ include Roar::Representer
12
+ include Roar::JSON
13
+ include Roar::Hypermedia
14
+
15
+ extend ClassMethods
16
+
17
+ self.representation_wrap= :collection # FIXME: move outside of this block for inheritance!
18
+
19
+ property :__template, :as => :template, :extend => lambda {|*| representable_attrs.collection_representers[:template] }, :class => Array
20
+ def __template
21
+ OpenStruct.new # TODO: handle preset values.
22
+ end
23
+
24
+ collection :queries, :extend => Roar::JSON::HyperlinkRepresenter, :class => lambda { |fragment,*| ::Hash }
25
+ def queries
26
+ compile_links_for(representable_attrs.collection_representers[:queries].link_configs)
27
+ end
28
+ def queries=(v)
29
+ end
30
+
31
+
32
+ def items
33
+ self
34
+ end
35
+ def items=(v)
36
+ replace(v)
37
+ end
38
+
39
+ property :__version, :as => :version
40
+ def __version
41
+ representable_attrs.collection_representers[:version]
42
+ end
43
+
44
+ property :__href, :as => :href
45
+ def __href
46
+ compile_links_for(representable_attrs.collection_representers[:href].link_configs).first.href
47
+ end
48
+
49
+
50
+
51
+ include ClientMethods
52
+ end
53
+ end
54
+
55
+ module ClassMethods
56
+ module PropertyWithRenderNil
57
+ def property(name, options={})
58
+ super(name, options.merge!(:render_nil => true))
59
+ end
60
+ end
61
+
62
+ # TODO: provide automatic copying from the ItemRepresenter here.
63
+ def template(&block)
64
+ mod = representable_attrs.collection_representers[:object_template] = Module.new do
65
+ include Roar::JSON
66
+ include Roar::JSON::CollectionJSON::DataMethods
67
+
68
+ extend PropertyWithRenderNil
69
+
70
+ module_exec(&block)
71
+
72
+ #self.representation_wrap = :template
73
+ def from_hash(hash, *args) # overridden in :template representer.
74
+ super(hash["template"])
75
+ end
76
+ end
77
+
78
+ representable_attrs.collection_representers[:template] = Module.new do
79
+ include Roar::JSON
80
+ include mod
81
+
82
+ #self.representation_wrap = false
83
+
84
+ # DISCUSS: currently we skip real deserialization here and just store the :data hash.
85
+ def from_hash(hash, *args)
86
+ replace(hash["data"])
87
+ end
88
+ end
89
+ end
90
+ def template_representer
91
+ representable_attrs.collection_representers[:object_template]
92
+ end
93
+
94
+ def queries(&block)
95
+ mod = representable_attrs.collection_representers[:queries] = Module.new do
96
+ include Roar::JSON
97
+ include Roar::Hypermedia
98
+
99
+ module_exec(&block)
100
+
101
+ def to_hash(*)
102
+ hash = super
103
+ hash["links"] # TODO: make it easier to render collection of links.
104
+ end
105
+ end
106
+ end
107
+
108
+ def items(options={}, &block)
109
+ collection :items, { :extend => lambda {|*| representable_attrs.collection_representers[:items] } }.merge!(options)
110
+
111
+ mod = representable_attrs.collection_representers[:items] = Module.new do
112
+ include Roar::JSON
113
+ include Roar::Hypermedia
114
+ include Roar::JSON::CollectionJSON::DataMethods
115
+ extend SharedClassMethodsBullshit
116
+
117
+ module_exec(&block)
118
+
119
+ # TODO: share with main module!
120
+ property :__href, :as => :href
121
+ def __href
122
+ compile_links_for(representable_attrs.collection_representers[:href].link_configs).first.href
123
+ end
124
+ def __href=(v)
125
+ @__href = Roar::Hypermedia::Hyperlink.new(:href => v)
126
+ end
127
+ def href
128
+ @__href
129
+ end
130
+ end
131
+ end
132
+
133
+ def version(v)
134
+ representable_attrs.collection_representers[:version] = v
135
+ end
136
+
137
+ module SharedClassMethodsBullshit
138
+ def href(&block)
139
+ mod = representable_attrs.collection_representers[:href] = Module.new do
140
+ include Roar::JSON
141
+ include Roar::Hypermedia
142
+
143
+
144
+ link(:href, &block)
145
+ end
146
+ end
147
+
148
+ def representable_attrs
149
+ super.tap do |attrs|
150
+ attrs.instance_eval do # FIXME: of course, this is WIP.
151
+ def collection_representers
152
+ @collection_representers ||= {}
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
158
+ include SharedClassMethodsBullshit
159
+ end
160
+
161
+ module DataMethods
162
+ def to_hash(*)
163
+ hash = super.tap do |hsh|
164
+ data = []
165
+ hsh.keys.each do |n|
166
+ next if ["href", "links"].include?(n)
167
+
168
+ v = hsh.delete(n.to_s)
169
+ data << {:name => n, :value => v} # TODO: get :prompt from Definition.
170
+ end
171
+ hsh[:data] = data
172
+ end
173
+ end
174
+
175
+ def from_hash(hash, *args)
176
+ data = {}
177
+ hash.delete("data").collect do |item|
178
+ data[item["name"]] = item["value"]
179
+ end
180
+ super(hash.merge!(data))
181
+ end
182
+ end
183
+
184
+ module ClientMethods
185
+ def __version=(v)
186
+ @__version = v
187
+ end
188
+ def version
189
+ @__version
190
+ end
191
+
192
+ def __href=(v)
193
+ @__href = Roar::Hypermedia::Hyperlink.new(:href => v)
194
+ end
195
+ def href
196
+ @__href
197
+ end
198
+
199
+ def __template=(v)
200
+ @__template = v
201
+ end
202
+ # DISCUSS: this might return a Template instance, soon.
203
+ def template
204
+ @__template
205
+ end
206
+ end
207
+ end
208
+ end
@@ -0,0 +1,223 @@
1
+ require 'roar/json'
2
+
3
+ module Roar
4
+ module JSON
5
+ # Including the JSON::HAL module in your representer will render and parse documents
6
+ # following the HAL specification: http://stateless.co/hal_specification.html
7
+ # Links will be embedded using the +_links+ key, nested resources with the +_embedded+ key.
8
+ #
9
+ # Embedded resources can be specified when calling #property or +collection using the
10
+ # :embedded => true option.
11
+ #
12
+ # Link arrays can be defined using +::links+.
13
+ #
14
+ # CURIEs are specified with the - surprise - +::curie+ class method.
15
+ #
16
+ # Example:
17
+ #
18
+ # module OrderRepresenter
19
+ # include Roar::Representer::JSON::HAL
20
+ #
21
+ # property :id
22
+ # collection :items, :class => Item, :extend => ItemRepresenter, :embedded => true
23
+ #
24
+ # link :self do
25
+ # "http://orders/#{id}"
26
+ # end
27
+ #
28
+ # links :self do
29
+ # [{:lang => "en", :href => "http://en.hit"},
30
+ # {:lang => "de", :href => "http://de.hit"}]
31
+ # end
32
+ #
33
+ # curies do
34
+ # [{:name => :doc,
35
+ # :href => "//docs/{rel}",
36
+ # :templated => true}
37
+ # ]
38
+ # end
39
+ # end
40
+ #
41
+ # Renders to
42
+ #
43
+ # "{\"id\":1,\"_embedded\":{\"items\":[{\"value\":\"Beer\",\"_links\":{\"self\":{\"href\":\"http://items/Beer\"}}}]},\"_links\":{\"self\":{\"href\":\"http://orders/1\"}}}"
44
+ module HAL
45
+ def self.included(base)
46
+ base.class_eval do
47
+ include Roar::JSON
48
+ include Links # overwrites #links_definition_options.
49
+ extend ClassMethods # overwrites #links_definition_options, again.
50
+ include Resources
51
+
52
+ def representable_mapper(*) # TODO: make this easier to override.
53
+ super.tap do |map|
54
+ map.extend Resources
55
+ end
56
+ end
57
+ end
58
+ end
59
+
60
+ module Resources
61
+ # Write the property to the +_embedded+ hash when it's a resource.
62
+ def compile_fragment(bin, doc)
63
+ embedded = bin[:embedded]
64
+ return super unless embedded
65
+ super(bin, doc[:_embedded] ||= {})
66
+ end
67
+
68
+ def uncompile_fragment(bin, doc)
69
+ embedded = bin[:embedded]
70
+ return super unless embedded
71
+ super(bin, doc["_embedded"] || {})
72
+ end
73
+ end
74
+
75
+ module ClassMethods
76
+ def links_definition_options
77
+ super.merge(:as => :_links)
78
+ end
79
+ end
80
+
81
+ class LinkCollection < Hypermedia::LinkCollection
82
+ def initialize(array_rels, *args)
83
+ super(*args)
84
+ @array_rels = array_rels.map(&:to_s)
85
+ end
86
+
87
+ def is_array?(rel)
88
+ @array_rels.include?(rel.to_s)
89
+ end
90
+ end
91
+
92
+ # Including this module in your representer will render and parse your embedded hyperlinks
93
+ # following the HAL specification: http://stateless.co/hal_specification.html
94
+ #
95
+ # module SongRepresenter
96
+ # include Roar::Representer::JSON
97
+ # include Roar::Representer::JSON::HAL::Links
98
+ #
99
+ # link :self { "http://self" }
100
+ # end
101
+ #
102
+ # Renders to
103
+ #
104
+ # {"links":{"self":{"href":"http://self"}}}
105
+ #
106
+ # Note that the HAL::Links module alone doesn't prepend an underscore to +links+. Use the JSON::HAL module for that.
107
+ module Links
108
+ def self.included(base)
109
+ base.extend ClassMethods # ::links_definition_options
110
+ base.send :include, Hypermedia
111
+ base.send :include, InstanceMethods
112
+ end
113
+
114
+ module InstanceMethods
115
+ private
116
+ def prepare_link_for(href, options)
117
+ return super(href, options) unless options[:array] # TODO: remove :array and use special instan
118
+
119
+ list = href.collect { |opts| Hypermedia::Hyperlink.new(opts.merge!(:rel => options[:rel])) }
120
+ LinkArray.new(list, options[:rel])
121
+ end
122
+
123
+ # TODO: move to LinksDefinition.
124
+ def link_array_rels
125
+ link_configs.collect { |cfg| cfg.first[:array] ? cfg.first[:rel] : nil }.compact
126
+ end
127
+ end
128
+
129
+
130
+ require 'representable/json/hash'
131
+ module LinkCollectionRepresenter
132
+ include Representable::JSON::Hash
133
+
134
+ values :extend => lambda { |item, *|
135
+ item.is_a?(Array) ? LinkArrayRepresenter : Roar::JSON::HyperlinkRepresenter },
136
+ :instance => lambda { |fragment, *| fragment.is_a?(LinkArray) ? fragment : Roar::Hypermedia::Hyperlink.new
137
+ }
138
+
139
+ def to_hash(options)
140
+ super.tap do |hsh| # TODO: cool: super(:exclude => [:rel]).
141
+ hsh.each { |k,v| v.delete("rel") }
142
+ end
143
+ end
144
+
145
+
146
+ def from_hash(hash, *args)
147
+ hash.each { |k,v| hash[k] = LinkArray.new(v, k) if is_array?(k) }
148
+
149
+ hsh = super(hash) # this is where :class and :extend do the work.
150
+
151
+ hsh.each { |k, v| v.merge!(:rel => k) }
152
+ hsh.values # links= expects [Hyperlink, Hyperlink]
153
+ end
154
+ end
155
+
156
+ # DISCUSS: we can probably get rid of this asset.
157
+ class LinkArray < Array
158
+ def initialize(elems, rel)
159
+ super(elems)
160
+ @rel = rel
161
+ end
162
+
163
+ attr_reader :rel
164
+
165
+ def merge!(attrs)
166
+ each { |lnk| lnk.merge!(attrs) }
167
+ end
168
+ end
169
+
170
+ require 'representable/json/collection'
171
+ module LinkArrayRepresenter
172
+ include Representable::JSON::Collection
173
+
174
+ items :extend => Roar::JSON::HyperlinkRepresenter,
175
+ :class => Roar::Hypermedia::Hyperlink
176
+
177
+ def to_hash(*)
178
+ super.tap do |ary|
179
+ ary.each { |lnk| rel = lnk.delete("rel") }
180
+ end
181
+ end
182
+ end
183
+
184
+
185
+ module ClassMethods
186
+ def links_definition_options
187
+ # property :links_array,
188
+ {
189
+ :as => :links,
190
+ :extend => HAL::Links::LinkCollectionRepresenter,
191
+ :instance => lambda { |*| LinkCollection.new(link_array_rels) }, # defined in InstanceMethods as this is executed in represented context.
192
+ :exec_context => :decorator,
193
+ }
194
+ end
195
+
196
+ # Use this to define link arrays. It accepts the shared rel attribute and an array of options per link object.
197
+ #
198
+ # links :self do
199
+ # [{:lang => "en", :href => "http://en.hit"},
200
+ # {:lang => "de", :href => "http://de.hit"}]
201
+ # end
202
+ def links(options, &block)
203
+ options = {:rel => options} if options.is_a?(Symbol)
204
+ options[:array] = true
205
+ link(options, &block)
206
+ end
207
+
208
+ # Add a CURIEs link section as defined in
209
+ #
210
+ # curies do
211
+ # [{:name => :doc,
212
+ # :href => "//docs/{rel}",
213
+ # :templated => true}
214
+ # ]
215
+ # end
216
+ def curies(&block)
217
+ links(:curies, &block)
218
+ end
219
+ end
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,3 @@
1
+ require "representable/json/hash"
2
+
3
+ Roar::JSON::Hash = Representable::JSON::Hash