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,228 @@
1
+ require 'roar/json'
2
+ require 'roar/decorator'
3
+
4
+ module Roar
5
+ module JSON
6
+ module JSONAPI
7
+ def self.included(base)
8
+ base.class_eval do
9
+ include Representable::JSON
10
+ include Roar::JSON::JSONAPI::Singular
11
+ include Roar::JSON::JSONAPI::Resource
12
+ include Roar::JSON::JSONAPI::Document
13
+
14
+ extend ForCollection
15
+
16
+ representable_attrs[:resource_representer] = Class.new(Resource::Representer)
17
+ end
18
+ end
19
+
20
+ module ForCollection
21
+ def for_collection # same API as representable. TODO: we could use ::collection_representer! here.
22
+ singular = self # e.g. Song::Representer
23
+
24
+ # this basically does Module.new { include Hash::Collection .. }
25
+ build_inline(nil, [Document::Collection, Representable::Hash::Collection, Roar::JSON], "", {}) do
26
+ items extend: singular, :parse_strategy => :sync
27
+
28
+ representable_attrs[:resource_representer] = singular.representable_attrs[:resource_representer]
29
+ representable_attrs[:meta_representer] = singular.representable_attrs[:meta_representer] # DISCUSS: do we need that?
30
+ representable_attrs[:_wrap] = singular.representable_attrs[:_wrap]
31
+ end
32
+ end
33
+ end
34
+
35
+
36
+ module Singular
37
+ def to_hash(options={})
38
+ # per resource:
39
+ super(:exclude => [:links]).tap do |hash|
40
+ hash["links"] = hash.delete("_links") if hash["_links"]
41
+ end
42
+ end
43
+
44
+ def from_hash(hash, options={})
45
+ hash["_links"] = hash["links"]
46
+ super
47
+ end
48
+ end
49
+
50
+
51
+ module Resource
52
+ # ::link is delegated to Representer which handles the hypermedia (rendering
53
+ # and parsing links).
54
+ class Representer < Roar::Decorator
55
+ include Roar::JSON
56
+ include Roar::Hypermedia
57
+
58
+ def self.links_definition_options
59
+ {
60
+ :extend => LinkCollectionRepresenter,
61
+ :exec_context => :decorator
62
+ }
63
+ end
64
+ end
65
+
66
+ def self.included(base)
67
+ base.extend Declarative # inject our ::link.
68
+ end
69
+
70
+ # New API for JSON-API representers.
71
+ module Declarative
72
+ def type(name=nil)
73
+ return super unless name # original name.
74
+ representable_attrs[:_wrap] = name.to_s
75
+ end
76
+
77
+ # Define global document links for the links: directive.
78
+ def link(*args, &block)
79
+ representable_attrs[:resource_representer].link(*args, &block)
80
+ end
81
+
82
+ # Per-model links.
83
+ def links(&block)
84
+ nested(:_links, &block)
85
+ end
86
+
87
+ # TODO: always create _links.
88
+ def has_one(name)
89
+ property :_links, :inherit => true, :use_decorator => true do # simply extend the Decorator _links.
90
+ property "#{name}_id", :as => name
91
+ end
92
+ end
93
+
94
+ def has_many(name)
95
+ property :_links, :inherit => true, :use_decorator => true do # simply extend the Decorator _links.
96
+ collection "#{name.to_s.sub(/s$/, "")}_ids", :as => name
97
+ end
98
+ end
99
+
100
+ def compound(&block)
101
+ nested(:linked, &block)
102
+ end
103
+
104
+ def meta(&block)
105
+ representable_attrs[:meta_representer] = Class.new(Roar::Decorator, &block)
106
+ end
107
+ end
108
+ end
109
+
110
+
111
+ # TODO: don't use Document for singular+wrap AND singular in collection (this way, we can get rid of the only_body)
112
+ module Document
113
+ def to_hash(options={})
114
+ # per resource:
115
+ res = super # render single resource or collection.
116
+ return res if options[:only_body]
117
+ # this is the only "dirty" part: this module is always included in the Singular document representer, when used in collection, we don't want it to do the extra work. this mechanism here might be changed soon.
118
+
119
+ to_document(res, options)
120
+ end
121
+
122
+ def from_hash(hash, options={})
123
+
124
+ return super(hash, options) if options[:only_body] # singular
125
+
126
+ super(from_document(hash)) # singular
127
+ end
128
+
129
+ private
130
+ def to_document(res, options)
131
+ links = render_links
132
+ meta = render_meta(options)
133
+ # FIXME: provide two different #to_document
134
+
135
+ if res.is_a?(Array)
136
+ compound = collection_compound!(res, {})
137
+ else
138
+ compound = compile_compound!(res.delete("linked"), {})
139
+ end
140
+
141
+ {representable_attrs[:_wrap] => res}.tap do |doc|
142
+ doc.merge!(links)
143
+ doc.merge!(meta)
144
+ doc.merge!("linked" => compound) if compound && compound.size > 0 # FIXME: make that like the above line.
145
+ end
146
+ end
147
+
148
+ def from_document(hash)
149
+ hash[representable_attrs[:_wrap]]
150
+ end
151
+
152
+ # Compiles the linked: section for compound objects in the document.
153
+ def collection_compound!(collection, compound)
154
+ collection.each { |res|
155
+ kv = res.delete("linked") or next
156
+
157
+ compile_compound!(kv, compound)
158
+ }
159
+
160
+ compound
161
+ end
162
+
163
+ # Go through {"album"=>{"title"=>"Hackers"}, "musicians"=>[{"name"=>"Eddie Van Halen"}, ..]} from linked:
164
+ # and wrap every item in an array.
165
+ def compile_compound!(linked, compound)
166
+ return unless linked
167
+
168
+ linked.each { |k,v| # {"album"=>{"title"=>"Hackers"}, "musicians"=>[{"name"=>"Eddie Van Halen"}, {"name"=>"Greg Howe"}]}
169
+ compound[k] ||= []
170
+
171
+ if v.is_a?(::Hash) # {"title"=>"Hackers"}
172
+ compound[k] << v
173
+ else
174
+ compound[k].push(*v) # [{"name"=>"Eddie Van Halen"}, {"name"=>"Greg Howe"}]
175
+ end
176
+
177
+ compound[k] = compound[k].uniq
178
+ }
179
+
180
+ compound
181
+ end
182
+
183
+ def render_links
184
+ representable_attrs[:resource_representer].new(represented).to_hash # creates links: section.
185
+ end
186
+
187
+ def render_meta(options)
188
+ # TODO: this will call collection.page etc, directly on the collection. we could allow using a "meta"
189
+ # object to hold this data.
190
+ # `meta call_meta: true` or something
191
+ return {"meta" => options["meta"]} if options["meta"]
192
+ return {} unless representer = representable_attrs[:meta_representer]
193
+ {"meta" => representer.new(represented).extend(Representable::Hash).to_hash}
194
+ end
195
+
196
+
197
+ module Collection
198
+ include Document
199
+
200
+ def to_hash(options={})
201
+ res = super(options.merge(:only_body => true))
202
+ to_document(res, options)
203
+ end
204
+
205
+ def from_hash(hash, options={})
206
+ hash = from_document(hash)
207
+ super(hash, options.merge(:only_body => true))
208
+ end
209
+ end
210
+ end
211
+
212
+
213
+ module LinkRepresenter
214
+ include Roar::JSON
215
+
216
+ property :href
217
+ property :type
218
+ end
219
+
220
+ require 'representable/json/hash'
221
+ module LinkCollectionRepresenter
222
+ include Representable::JSON::Hash
223
+
224
+ values :extend => LinkRepresenter # TODO: parsing.
225
+ end
226
+ end
227
+ end
228
+ end
data/lib/roar/json.rb ADDED
@@ -0,0 +1,55 @@
1
+ require 'roar/representer'
2
+ require 'roar/hypermedia'
3
+ require 'representable/json'
4
+
5
+ module Roar
6
+ module JSON
7
+ def self.included(base)
8
+ base.class_eval do
9
+ include Representer
10
+ include Representable::JSON
11
+
12
+ extend ClassMethods
13
+ include InstanceMethods # otherwise Representable overrides our #to_json.
14
+ end
15
+ end
16
+
17
+ module InstanceMethods
18
+ def from_json(document, options={})
19
+ document = '{}' if document.nil? or document.empty?
20
+
21
+ super
22
+ end
23
+
24
+ # Generic entry-point for rendering.
25
+ def serialize(*args)
26
+ to_json(*args)
27
+ end
28
+
29
+ def deserialize(*args)
30
+ from_json(*args)
31
+ end
32
+ end
33
+
34
+
35
+ module ClassMethods
36
+ # TODO: move to instance method, or remove?
37
+ def links_definition_options
38
+ # FIXME: this doesn't belong into the generic JSON representer.
39
+ {
40
+ :collection => true,
41
+ :class => Hypermedia::Hyperlink,
42
+ :extend => HyperlinkRepresenter,
43
+ :exec_context => :decorator,
44
+ }
45
+ end
46
+ end
47
+
48
+
49
+ require "representable/json/hash"
50
+ # Represents a hyperlink in standard roar+json hash representation.
51
+ module HyperlinkRepresenter
52
+ include Representable::JSON::Hash
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,11 @@
1
+ require 'representable'
2
+
3
+ module Roar
4
+ # generic features can be included here and will be available in all format-specific representers.
5
+ module Representer
6
+ def self.included(base)
7
+ super
8
+ base.send(:include, Representable)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,49 @@
1
+ gem 'faraday'
2
+ require 'faraday'
3
+
4
+ module Roar
5
+ module Transport
6
+ # Advanced implementation of the HTTP verbs with the Faraday HTTP library
7
+ # (which can, in turn, use adapters based on Net::HTTP or libcurl)
8
+ #
9
+ # Depending on how the Faraday middleware stack is configured, this
10
+ # Transport can support features such as HTTP error code handling,
11
+ # redirects, etc.
12
+ #
13
+ # @see http://rubydoc.info/gems/faraday/file/README.md Faraday README
14
+ class Faraday
15
+
16
+ def get_uri(options)
17
+ build_connection(options[:uri], options[:as]).get
18
+ end
19
+
20
+ def post_uri(options)
21
+ build_connection(options[:uri], options[:as]).post(nil, options[:body])
22
+ end
23
+
24
+ def put_uri(options)
25
+ build_connection(options[:uri], options[:as]).put(nil, options[:body])
26
+ end
27
+
28
+ def patch_uri(options)
29
+ build_connection(options[:uri], options[:as]).patch(nil, options[:body])
30
+ end
31
+
32
+ def delete_uri(options)
33
+ build_connection(options[:uri], options[:as]).delete
34
+ end
35
+
36
+ private
37
+
38
+ def build_connection(uri, as)
39
+ ::Faraday::Connection.new(
40
+ :url => uri,
41
+ :headers => { :accept => as, :content_type => as }
42
+ ) do |builder|
43
+ builder.use ::Faraday::Response::RaiseError
44
+ builder.adapter ::Faraday.default_adapter
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,77 @@
1
+ require "net/http"
2
+ require "openssl"
3
+
4
+ module Roar
5
+ module Transport
6
+ class NetHTTP
7
+ class Request # TODO: implement me.
8
+ def initialize(options)
9
+ @uri = parse_uri(options[:uri]) # TODO: add :uri.
10
+ @as = options[:as]
11
+ @body = options[:body]
12
+ @options = options
13
+
14
+ @http = Net::HTTP.new(uri.host, uri.port)
15
+ unless options[:pem_file].nil?
16
+ pem = File.read(options[:pem_file])
17
+ @http.use_ssl = true
18
+ @http.cert = OpenSSL::X509::Certificate.new(pem)
19
+ @http.key = OpenSSL::PKey::RSA.new(pem)
20
+ @http.verify_mode = options[:ssl_verify_mode].nil? ? OpenSSL::SSL::VERIFY_PEER : options[:ssl_verify_mode]
21
+ end
22
+ end
23
+
24
+ def call(what)
25
+ @req = what.new(uri.request_uri)
26
+
27
+ # if options[:ssl]
28
+ # uri.port = Net::HTTP.https_default_port()
29
+ # end
30
+ https!
31
+ basic_auth!
32
+
33
+ req.content_type = as
34
+ req["accept"] = as # TODO: test me. # DISCUSS: if Accept is not set, rails treats this request as as "text/html".
35
+ req.body = body if body
36
+
37
+ yield req if block_given?
38
+
39
+ http.request(req).tap do |res|
40
+ handle_error!(res)
41
+ end
42
+ end
43
+
44
+ def get
45
+ call(Net::HTTP::Get)
46
+ end
47
+
48
+ private
49
+ attr_reader :uri, :as, :body, :options, :req, :http
50
+
51
+ def parse_uri(url)
52
+ uri = URI(url)
53
+ raise "Incorrect URL `#{url}`. Maybe you forgot http://?" if uri.instance_of?(URI::Generic)
54
+ uri
55
+ end
56
+
57
+ def https!
58
+ return unless uri.scheme == 'https'
59
+
60
+ @http.use_ssl = true
61
+ @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
62
+ end
63
+
64
+ def basic_auth!
65
+ return unless options[:basic_auth]
66
+
67
+ @req.basic_auth(*options[:basic_auth])
68
+ end
69
+
70
+ def handle_error!(res)
71
+ status = res.code.to_i
72
+ raise Error.new(res) unless status >= 200 and status < 300
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,49 @@
1
+ require 'roar/transport/net_http/request'
2
+
3
+ module Roar
4
+ # Implements the (HTTP) transport interface with Net::HTTP.
5
+ module Transport
6
+ # Low-level interface for HTTP. The #get_uri and friends accept an options and an optional block, invoke
7
+ # the HTTP request and return the request object.
8
+ #
9
+ # The following options are available:
10
+ class NetHTTP
11
+
12
+ def get_uri(*options, &block)
13
+ call(Net::HTTP::Get, *options, &block)
14
+ end
15
+
16
+ def post_uri(*options, &block)
17
+ call(Net::HTTP::Post, *options, &block)
18
+ end
19
+
20
+ def put_uri(*options, &block)
21
+ call(Net::HTTP::Put, *options, &block)
22
+ end
23
+
24
+ def delete_uri(*options, &block)
25
+ call(Net::HTTP::Delete, *options, &block)
26
+ end
27
+
28
+ def patch_uri(*options, &block)
29
+ call(Net::HTTP::Patch, *options, &block)
30
+ end
31
+
32
+ private
33
+ def call(what, options, &block)
34
+ # TODO: generically handle return codes.
35
+ Request.new(options).call(what, &block)
36
+ end
37
+ end
38
+
39
+ # Wraps the original response from NetHttp and provides it via #response.
40
+ class Error < RuntimeError # TODO: raise this from Faraday, too.
41
+ def initialize(response)
42
+ @response = response
43
+ super("Roar error: #{response}")
44
+ end
45
+
46
+ attr_reader :response
47
+ end
48
+ end
49
+ end
data/lib/roar/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Roar
2
- VERSION = "0.0.1.alpha1"
2
+ VERSION = "1.0.0"
3
3
  end
data/lib/roar/xml.rb ADDED
@@ -0,0 +1,54 @@
1
+ require 'roar/representer'
2
+ require 'roar/hypermedia'
3
+ require 'representable/xml'
4
+
5
+ module Roar
6
+ # Includes #from_xml and #to_xml into your represented object.
7
+ # In addition to that, some more options are available when declaring properties.
8
+ module XML
9
+ def self.included(base)
10
+ base.class_eval do
11
+ include Representer # Roar::Representer, this is needed for Rails URL helpers
12
+ include Representable::XML
13
+
14
+ extend ClassMethods
15
+ include InstanceMethods # otherwise Representable overrides our #to_xml.
16
+ end
17
+ end
18
+
19
+ module InstanceMethods
20
+ # Generic entry-point for rendering.
21
+ def serialize(*args)
22
+ to_xml(*args)
23
+ end
24
+
25
+ def deserialize(*args)
26
+ from_xml(*args)
27
+ end
28
+ end
29
+
30
+
31
+ module ClassMethods
32
+ include Representable::XML::ClassMethods
33
+
34
+ def links_definition_options
35
+ # FIXME: this doesn't belong into the generic XML representer.
36
+ {
37
+ :as => :link,
38
+ :collection => true,
39
+ :class => Hypermedia::Hyperlink,
40
+ :extend => XML::HyperlinkRepresenter,
41
+ :exec_context => :decorator,
42
+ } # TODO: merge with JSON.
43
+ end
44
+ end
45
+
46
+
47
+ require 'representable/xml/hash'
48
+ module HyperlinkRepresenter
49
+ include Representable::XML::AttributeHash
50
+
51
+ self.representation_wrap = :link
52
+ end
53
+ end
54
+ end
data/lib/roar.rb CHANGED
@@ -1,3 +1,6 @@
1
+ require 'roar/version'
1
2
  module Roar
2
- # Your code goes here...
3
+ def self.root
4
+ File.expand_path '../..', __FILE__
5
+ end
3
6
  end
data/roar.gemspec CHANGED
@@ -1,4 +1,3 @@
1
- # -*- encoding: utf-8 -*-
2
1
  $:.push File.expand_path("../lib", __FILE__)
3
2
  require "roar/version"
4
3
 
@@ -10,12 +9,22 @@ Gem::Specification.new do |s|
10
9
  s.email = ["apotonick@gmail.com"]
11
10
  s.homepage = "http://rubygems.org/gems/roar"
12
11
  s.summary = %q{Resource-oriented architectures in Ruby.}
13
- s.description = %q{RESTful, resource-oriented architectures in Ruby.}
14
-
15
- s.rubyforge_project = "roar"
12
+ s.description = %q{Streamlines the development of RESTful, resource-oriented architectures in Ruby.}
13
+ s.license = 'MIT'
16
14
 
17
15
  s.files = `git ls-files`.split("\n")
18
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
16
+ s.test_files = `git ls-files -- {test}/*`.split("\n")
19
17
  s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
18
  s.require_paths = ["lib"]
19
+
20
+ s.add_runtime_dependency "representable", ">= 2.0.1", "<= 3.0.0"
21
+
22
+ s.add_development_dependency "rake", ">= 0.10.1"
23
+ s.add_development_dependency "test_xml", "0.1.6"
24
+ s.add_development_dependency "minitest", ">= 5.4.2"
25
+ s.add_development_dependency "sinatra"
26
+ s.add_development_dependency "sinatra-contrib"
27
+ s.add_development_dependency "virtus", ">= 1.0.0"
28
+ s.add_development_dependency "faraday"
29
+ s.add_development_dependency "json"
21
30
  end
@@ -0,0 +1,36 @@
1
+ require 'test_helper'
2
+ require 'roar/client'
3
+
4
+ class ClientTest < MiniTest::Spec
5
+ representer_for([Roar::Representer]) do
6
+ property :name
7
+ property :band
8
+ end
9
+
10
+ let(:song) { Object.new.extend(rpr).extend(Roar::Client) }
11
+
12
+ it "adds accessors" do
13
+ song.name = "Social Suicide"
14
+ song.band = "Bad Religion"
15
+ assert_equal "Social Suicide", song.name
16
+ assert_equal "Bad Religion", song.band
17
+ end
18
+
19
+ describe "links" do
20
+ representer_for([Roar::JSON, Roar::Hypermedia]) do
21
+ property :name
22
+ link(:self) { never_call_me! }
23
+ end
24
+
25
+ it "suppresses rendering" do
26
+ song.name = "Silenced"
27
+ song.to_json.must_equal %{{\"name\":\"Silenced\",\"links\":[]}}
28
+ end
29
+
30
+ # since this is considered dangerous, we test the mutuable options.
31
+ it "adds links: false to options" do
32
+ song.to_hash(options = {})
33
+ options.must_equal({:links => false})
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,23 @@
1
+ require 'test_helper'
2
+ require 'roar/coercion'
3
+
4
+ class CoercionFeatureTest < MiniTest::Spec
5
+ describe "Coercion" do
6
+ class ImmigrantSong
7
+ include Roar::JSON
8
+ include Roar::Coercion
9
+
10
+ property :composed_at, :type => DateTime, :default => "May 12th, 2012"
11
+
12
+ attr_accessor :composed_at
13
+ def composed_at=(v) # in ruby 2.2, #label= is not there, all at sudden. what *is* that?
14
+ @composed_at = v
15
+ end
16
+ end
17
+
18
+ it "coerces into the provided type" do
19
+ song = ImmigrantSong.new.from_json("{\"composed_at\":\"November 18th, 1983\"}")
20
+ assert_equal DateTime.parse("Fri, 18 Nov 1983 00:00:00 +0000"), song.composed_at
21
+ end
22
+ end
23
+ end