goliath-chimp 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ language: ruby
2
+ rvm:
3
+ - 1.9.3
4
+
5
+ notifications:
6
+ email: false
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
4
+
5
+ group :development do
6
+ gem 'rake', '>= 0.8.7'
7
+ gem 'rspec', '~> 2'
8
+ gem 'simplecov', '~> 0.8'
9
+ end
data/LICENSE.md ADDED
@@ -0,0 +1,95 @@
1
+ # License for Goliath-Chimp
2
+
3
+ Goliath-Chimp is __Copyright (c) 2014 Infochimps, Inc__
4
+
5
+ This code is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an **AS IS** BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ __________________________________________________________________________
12
+
13
+ # Apache License
14
+
15
+
16
+ Apache License
17
+ Version 2.0, January 2004
18
+ http://www.apache.org/licenses/
19
+
20
+ _TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION_
21
+
22
+ ## 1. Definitions.
23
+
24
+ * **License** shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
25
+
26
+ * **Licensor** shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
27
+
28
+ * **Legal Entity** shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
29
+
30
+ * **You** (or **Your**) shall mean an individual or Legal Entity exercising permissions granted by this License.
31
+
32
+ * **Source** form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
33
+
34
+ * **Object** form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
35
+
36
+ * **Work** shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
37
+
38
+ * **Derivative Works** shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
39
+
40
+ * **Contribution** shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
41
+
42
+ * **Contributor** shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
43
+
44
+ ## 2. Grant of Copyright License.
45
+
46
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
47
+
48
+ ## 3. Grant of Patent License.
49
+
50
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
51
+
52
+ ## 4. Redistribution.
53
+
54
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
55
+
56
+ - (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
57
+ - (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
58
+ - (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
59
+ - (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
60
+
61
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
62
+
63
+ ## 5. Submission of Contributions.
64
+
65
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
66
+
67
+ ## 6. Trademarks.
68
+
69
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
70
+
71
+ ## 7. Disclaimer of Warranty.
72
+
73
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
74
+
75
+ ## 8. Limitation of Liability.
76
+
77
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
78
+
79
+ ## 9. Accepting Warranty or Additional Liability.
80
+
81
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
82
+
83
+ _END OF TERMS AND CONDITIONS_
84
+
85
+ ## APPENDIX: How to apply the Apache License to your work.
86
+
87
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets `[]` replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
88
+
89
+ > Copyright [yyyy] [name of copyright owner]
90
+ >
91
+ > Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
92
+ >
93
+ > http://www.apache.org/licenses/LICENSE-2.0
94
+ >
95
+ > Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
data/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # Goliath::Chimp
2
+
3
+ [![Build Status](https://travis-ci.org/infochimps-labs/goliath-chimp.png?branch=master)](https://travis-ci.org/infochimps-labs/goliath-chimp)
4
+
5
+ TODO: Write a gem description
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 'goliath-chimp', require: 'goliath/chimp'
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install goliath-chimp
20
+
21
+ ## Usage
22
+
23
+ TODO: Write usage instructions here
24
+
25
+ ## Contributing
26
+
27
+ 1. Fork it
28
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
29
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
30
+ 4. Push to the branch (`git push origin my-new-feature`)
31
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new
5
+
6
+ desc 'Run RSpec code examples with SimpleCov'
7
+ task :coverage do
8
+ ENV['RACK_COVERAGE'] = 'true'
9
+ Rake::Task[:spec].invoke
10
+ end
11
+
12
+ task default: [:spec]
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'goliath/chimp/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = 'goliath-chimp'
8
+ s.version = Goliath::Chimp::VERSION
9
+ s.authors = ['Travis Dempsey']
10
+ s.email = ['travis@infochimps.com']
11
+ s.homepage = 'https://github.com/infochimps-labs/goliath-chimp'
12
+ s.licenses = ['Apache 2.0']
13
+ s.summary = 'Collection of Chimp-inspired Goliath/Rack utility classes'
14
+ s.description = <<-DESC.gsub(/^ {4}/, '').chomp
15
+ Goliath Chimp
16
+
17
+ A collection of reusable Rack classes and other goodies
18
+ for use in Goliath APIs.
19
+ DESC
20
+
21
+ s.files = `git ls-files`.split($/)
22
+ s.executables = s.files.grep(/^bin/){ |f| File.basename(f) }
23
+ s.test_files = s.files.grep(/^spec/)
24
+ s.require_paths = ['lib']
25
+
26
+ s.add_dependency('goliath', '~> 1')
27
+ s.add_dependency('gorillib', '~> 0.5')
28
+ s.add_dependency('multi_json', '~> 1.8')
29
+ end
@@ -0,0 +1,15 @@
1
+ require 'goliath'
2
+ require 'gorillib/metaprogramming/concern'
3
+ require 'multi_json'
4
+
5
+ require 'goliath/chimp/handler'
6
+ require 'goliath/chimp/rack/api_version'
7
+ require 'goliath/chimp/rack/control_methods'
8
+ require 'goliath/chimp/rack/force_content_type'
9
+
10
+ require 'goliath/chimp/rack/formatters/json'
11
+
12
+ require 'goliath/chimp/rack/validation/routes'
13
+ require 'goliath/chimp/rack/validation/required_routes'
14
+ require 'goliath/chimp/rack/validation/route_handler'
15
+
@@ -0,0 +1,52 @@
1
+ module Goliath::Chimp
2
+ module Handler
3
+ #
4
+ # This handler mixin is designed to handle ONLY the
5
+ # designated crud methods. Define your specific handler's
6
+ # behavior and this mixin will take care of the validation
7
+ # and response behavior of any missing methods.
8
+ #
9
+ # Example:
10
+ #
11
+ # class SimpleHandler
12
+ # include Goliath::Chimp::Handler
13
+ #
14
+ # def create doc
15
+ # # insert a record into the database
16
+ # end
17
+ #
18
+ # def retrieve id
19
+ # # retrieve a record from the database
20
+ # end
21
+ # end
22
+ #
23
+ # begin
24
+ # SimpleHandler.new.delete 'id'
25
+ #G rescue Goliath::Validation::Error => e
26
+ # [e.status_code, {}, { error: e.message }
27
+ # end
28
+ # #=> [405, {}, {:error=>"Operation delete not allowed for SimpleHandler. Valid operations are ["create", "retrieve"]"}]
29
+ #
30
+ include Gorillib::Concern
31
+ include Goliath::Rack::Validator
32
+
33
+ def crud_methods
34
+ %w[ search create retrieve update delete ]
35
+ end
36
+
37
+ def valid_operations
38
+ crud_methods.select{ |m| self.respond_to? m }
39
+ end
40
+
41
+ def invalid_operation name
42
+ message = "Operation #{name} not allowed for #{self.class}. Valid operations are #{valid_operations}"
43
+ Goliath::Validation::MethodNotAllowedError.new message
44
+ end
45
+
46
+ def method_missing(name, *args, &blk)
47
+ super unless crud_methods.include? name.to_s
48
+ raise invalid_operation name
49
+ end
50
+
51
+ end
52
+ end
@@ -0,0 +1,29 @@
1
+ module Goliath::Chimp
2
+ module Rack
3
+ class ApiVersion
4
+ include Goliath::Rack::AsyncMiddleware
5
+
6
+ attr_reader :path, :version, :version_header
7
+
8
+ def initialize(app, version, options = {})
9
+ @app = app
10
+ @version = version
11
+ @path = options[:path] || '/version'
12
+ @version_header = { "X-#{options[:api] || 'Api'}-Version" => version }
13
+ end
14
+
15
+ def call env
16
+ if env['PATH_INFO'] == path
17
+ [200, version_header, version]
18
+ else
19
+ super
20
+ end
21
+ end
22
+
23
+ def post_process(env, status, headers, body)
24
+ headers ||= {}
25
+ [status, headers.merge(version_header), body]
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,20 @@
1
+ module Goliath::Chimp
2
+ module Rack
3
+ class ControlMethods
4
+
5
+ attr_reader :method_map
6
+
7
+ def initialize(app, map = {})
8
+ @app = app ; @method_map = map
9
+ end
10
+
11
+ def call env
12
+ request_method = (env['HTTP_X_METHOD'] || env['REQUEST_METHOD']).to_s.upcase
13
+ if control_method = method_map[request_method]
14
+ env['control_method'] = control_method
15
+ end
16
+ @app.call env
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,17 @@
1
+ module Goliath::Chimp
2
+ module Rack
3
+ class ForceContentType
4
+
5
+ attr_reader :content_type
6
+
7
+ def initialize(app, content_type)
8
+ @app = app ; @content_type = content_type
9
+ end
10
+
11
+ def call env
12
+ env['CONTENT_TYPE'] = env['HTTP_ACCEPT'] = content_type
13
+ @app.call env
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,28 @@
1
+ module Goliath::Chimp
2
+ module Rack
3
+ module Formatters
4
+ class JSON
5
+ #
6
+ # This class is identical to the formatter class
7
+ # Goliath::Rack::Formatters::JSON except that it
8
+ # allows for pretty printing of a response body;
9
+ # something that comes in handy when constructing
10
+ # interactive HTTP APIs.
11
+ #
12
+ include Goliath::Rack::AsyncMiddleware
13
+
14
+ def post_process(env, status, headers, body)
15
+ pretty = !!env['params']['pretty'] rescue false
16
+ if json_response? headers
17
+ body = MultiJson.dump(body, pretty: pretty)
18
+ end
19
+ [status, headers, body]
20
+ end
21
+
22
+ def json_response? headers
23
+ headers['Content-Type'] =~ /^application\/(json|javascript)/
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,25 @@
1
+ module Goliath::Chimp
2
+ module Rack::Validation
3
+ class RequiredRoutes
4
+ include Goliath::Rack::Validator
5
+
6
+ attr_reader :route_key, :select_routes
7
+
8
+ def initialize(app, key, routes = {})
9
+ @app = app
10
+ @route_key = key
11
+ @select_routes = routes
12
+ end
13
+
14
+ def call env
15
+ if endpoint = env['routes'][route_key] rescue nil
16
+ route, required = select_routes.detect{ |name, required| name === endpoint }
17
+ return validation_error(400, "A #{required} route is required for #{endpoint}") if required && env['routes'][required].nil?
18
+ @app.call env
19
+ else
20
+ @app.call env
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,26 @@
1
+ module Goliath::Chimp
2
+ module Rack::Validation
3
+ class RouteHandler
4
+ include Goliath::Rack::Validator
5
+
6
+ attr_reader :route_key, :handler_map
7
+
8
+ def initialize(app, key, map = {})
9
+ @app = app
10
+ @route_key = key
11
+ @handler_map = map
12
+ end
13
+
14
+ def call env
15
+ endpoint = env['routes'][route_key] rescue nil
16
+ name, handler = handler_map.detect{ |name, handler| name === endpoint }
17
+ if handler
18
+ env['handler'] = handler
19
+ @app.call env
20
+ else
21
+ validation_error(400, "No handler found for #{route_key} <#{endpoint}>")
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,27 @@
1
+ module Goliath::Chimp
2
+ module Rack::Validation
3
+ class Routes
4
+ include Goliath::Rack::Validator
5
+
6
+ attr_reader :route_regex, :printable_route
7
+
8
+ def initialize(app, regex, printable = nil)
9
+ @app = app
10
+ @route_regex = regex
11
+ @printable_route = printable || regex.inspect
12
+ end
13
+
14
+ def call env
15
+ if path = env[Goliath::Request::REQUEST_PATH].match(route_regex)
16
+ env['routes'] ||= {}
17
+ path.names.each do |segment|
18
+ env['routes'][segment.to_sym] = path[segment]
19
+ end
20
+ @app.call env
21
+ else
22
+ validation_error(400, "Invalid route. Must match #{printable_route}")
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,5 @@
1
+ module Goliath
2
+ module Chimp
3
+ VERSION = '0.0.1'
4
+ end
5
+ end
@@ -0,0 +1,32 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Handler do
4
+ subject{ Object.new.extend described_class }
5
+
6
+ context '#invalid_operation' do
7
+ before do
8
+ subject.define_singleton_method(:create){ }
9
+ subject.define_singleton_method(:retrieve){ }
10
+ end
11
+
12
+ it 'returns a validation error listing available operations' do
13
+ message = 'Operation update not allowed for Object. Valid operations are ["create", "retrieve"]'
14
+ subject.invalid_operation(:update).should be_a(Goliath::Validation::MethodNotAllowedError)
15
+ subject.invalid_operation(:update).message.should eq(message)
16
+ subject.invalid_operation(:update).status_code.should eq('405')
17
+ end
18
+ end
19
+
20
+ context '#method_missing', 'when crud method' do
21
+ it 'raises a goliath http error' do
22
+ message = 'Operation update not allowed for Object. Valid operations are []'
23
+ expect{ subject.update }.to raise_error(Goliath::Validation::MethodNotAllowedError, message)
24
+ end
25
+ end
26
+
27
+ context '#method_missing', 'when other method' do
28
+ it 'raises a NoMethodError normally' do
29
+ expect{ subject.foobar }.to raise_error(NoMethodError)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,36 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::ApiVersion do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { Hash.new }
7
+ let(:version){ '1.2' }
8
+ subject { described_class.new(app, version, api: 'Jumanji') }
9
+
10
+ context '#call', 'when /version' do
11
+ it 'does not call the app' do
12
+ app.should_not_receive(:call)
13
+ env['PATH_INFO'] = '/version'
14
+ subject.call env
15
+ end
16
+
17
+ it 'returns the version' do
18
+ env['PATH_INFO'] = '/version'
19
+ subject.call(env).should eq([200, { 'X-Jumanji-Version' => version }, version])
20
+ end
21
+ end
22
+
23
+ context '#call', 'when /^version' do
24
+ it 'does nothing' do
25
+ app.should_receive(:call)
26
+ env['PATH_INFO'] = '/foobar'
27
+ subject.call env
28
+ end
29
+ end
30
+
31
+ context '#post_process' do
32
+ it 'add a server version header to all responses' do
33
+ subject.post_process(env, 200, {}, 'OK').should eq([200, { 'X-Jumanji-Version' => version }, 'OK'])
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,32 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::ControlMethods do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { Hash.new }
7
+ let(:methods){ { 'GET' => :grab, 'PUT' => :shelve } }
8
+ subject { described_class.new(app, methods) }
9
+
10
+ context '#call', 'with matching http method' do
11
+ it 'assigns a control method' do
12
+ env['REQUEST_METHOD'] = 'GET'
13
+ app.should_receive(:call).with(env){ |e| e['control_method'].should eq(:grab) }
14
+ subject.call env
15
+ end
16
+
17
+ it 'uses HTTP_X over REQUEST' do
18
+ env['REQUEST_METHOD'] = 'GET'
19
+ env['HTTP_X_METHOD'] = 'PUT'
20
+ app.should_receive(:call).with(env){ |e| e['control_method'].should eq(:shelve) }
21
+ subject.call env
22
+ end
23
+ end
24
+
25
+ context '#call', 'without a matching http method' do
26
+ it 'does not assign a control method' do
27
+ env['REQUEST_METHOD'] = 'HEAD'
28
+ app.should_receive(:call).with(env){ |e| e['control_method'].should be_nil }
29
+ subject.call env
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,22 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::ForceContentType do
4
+
5
+ let(:app){ double :app }
6
+ let(:env){ Hash.new }
7
+ subject{ described_class.new(app, 'text/xml') }
8
+
9
+ context '#call' do
10
+ it 'overrides content send type' do
11
+ env['CONTENT_TYPE'] = 'application/json'
12
+ app.should_receive(:call).with(env){ |e| e['CONTENT_TYPE'].should eq('text/xml') }
13
+ subject.call env
14
+ end
15
+
16
+ it 'overrides content accept type' do
17
+ env['HTTP_ACCEPT'] = 'application/json'
18
+ app.should_receive(:call).with(env){ |e| e['HTTP_ACCEPT'].should eq('text/xml') }
19
+ subject.call env
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,33 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::Formatters::JSON do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { { 'params' => {} } }
7
+ let(:status) { 200 }
8
+ let(:headers){ Hash.new }
9
+ subject { described_class.new app }
10
+
11
+ context '#post_process', 'when the content-type is set to JSON' do
12
+ it 'serializes the body as JSON' do
13
+ headers['Content-Type'] = 'application/json'
14
+ subject.post_process(env, status, headers, { foo: 'bar' }).should eq([status, headers, '{"foo":"bar"}'])
15
+ end
16
+ end
17
+
18
+ context '#post_process', 'when the content-type is not set to JSON' do
19
+ it 'does not serializes the body' do
20
+ headers['Content-Type'] = 'application/xml'
21
+ subject.post_process(env, status, headers, { foo: 'bar' }).should eq([status, headers, { foo: 'bar' }])
22
+ end
23
+ end
24
+
25
+ context '#post_process', 'when the content-type is set to JSON and pretty is a param' do
26
+ it 'serializes the body as pretty-printed JSON' do
27
+ headers['Content-Type'] = 'application/json'
28
+ env['params']['pretty'] = true
29
+ MultiJson.should_receive(:dump).with({ foo: { bar: 'baz' } }, pretty: true).and_return('{\n "foo":{\n "bar":"baz"\n }\n}')
30
+ subject.post_process(env, status, headers, { foo: { bar: 'baz' } }).should eq([status, headers, '{\n "foo":{\n "bar":"baz"\n }\n}'])
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,33 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::Validation::RequiredRoutes do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { Hash.new.merge routes }
7
+ let(:required){ { /^foo$/ => :id, 'bar' => :id } }
8
+ subject { described_class.new(app, :endpoint, required) }
9
+
10
+ context '#call', 'with selected route' do
11
+ let(:routes){ { 'routes' => { endpoint: 'foo' } } }
12
+
13
+ it 'raises a validation error if required route is missing' do
14
+ subject.call(env).should eq([400, {}, { error: 'A id route is required for foo' }])
15
+ end
16
+
17
+ it 'does not raise an error if required route is present' do
18
+ routes.merge!('routes' => { id: '123' })
19
+ app.should_receive(:call).with(env)
20
+ subject.call env
21
+ end
22
+ end
23
+
24
+ context '#call', 'with unselected route' do
25
+ let(:routes){ { 'routes' => { endpoint: 'baz' } } }
26
+
27
+ it 'does not raise an error when selected route does not match' do
28
+ app.should_receive(:call).with(env)
29
+ subject.call env
30
+ end
31
+ end
32
+
33
+ end
@@ -0,0 +1,35 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::Validation::RouteHandler do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { Hash.new.merge routes }
7
+ let(:handlers){ { /^foo$/ => 'FooHandler', 'bar' => 'BarHandler' } }
8
+ subject { described_class.new(app, :endpoint, handlers) }
9
+
10
+ context '#call', 'handler regex' do
11
+ let(:routes){ { 'routes' => { endpoint: 'foo' } } }
12
+
13
+ it 'assigns a handler if selected route matches' do
14
+ app.should_receive(:call).with(env){ |e| e['handler'].should eq('FooHandler') }
15
+ subject.call env
16
+ end
17
+ end
18
+
19
+ context '#call', 'handler string' do
20
+ let(:routes){ { 'routes' => { endpoint: 'bar' } } }
21
+
22
+ it 'assigns a handler if selected route matches' do
23
+ app.should_receive(:call).with(env){ |e| e['handler'].should eq('BarHandler') }
24
+ subject.call env
25
+ end
26
+ end
27
+
28
+ context '#call', 'no handler' do
29
+ let(:routes){ { 'routes' => { endpoint: 'baz' } } }
30
+
31
+ it 'raises a validation error' do
32
+ subject.call(env).should eq([400, {}, { error: "No handler found for endpoint <baz>" }])
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,27 @@
1
+ require 'spec_helper'
2
+
3
+ describe Goliath::Chimp::Rack::Validation::Routes do
4
+
5
+ let(:app) { double :app }
6
+ let(:env) { Hash.new }
7
+ let(:regex){ Regexp.new(/^\/final\/fantasy\/(?<version>.*)$/) }
8
+ subject { described_class.new(app, regex, '/final/fantasy/<version>') }
9
+
10
+ context '#call', 'with an invalid path' do
11
+ it 'returns a validation error' do
12
+ env['REQUEST_PATH'] = '/foo/bar/baz'
13
+ subject.call(env).should eq([400, {}, { error: 'Invalid route. Must match /final/fantasy/<version>' }])
14
+ end
15
+ end
16
+
17
+ context '#call', 'with a valid path' do
18
+ it 'extracts all match groups as params' do
19
+ env['REQUEST_PATH'] = '/final/fantasy/vii'
20
+ app.should_receive(:call).with(env) do |e|
21
+ e['routes'].should be_a(Hash)
22
+ e['routes'][:version].should eq('vii')
23
+ end
24
+ subject.call env
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,8 @@
1
+ if ENV['RACK_COVERAGE']
2
+ require 'simplecov'
3
+ SimpleCov.start
4
+ end
5
+
6
+ require 'goliath/chimp'
7
+
8
+ Goliath.run_app_on_exit = false
metadata ADDED
@@ -0,0 +1,140 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: goliath-chimp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Travis Dempsey
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2014-01-30 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: goliath
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1'
30
+ - !ruby/object:Gem::Dependency
31
+ name: gorillib
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ~>
36
+ - !ruby/object:Gem::Version
37
+ version: '0.5'
38
+ type: :runtime
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ~>
44
+ - !ruby/object:Gem::Version
45
+ version: '0.5'
46
+ - !ruby/object:Gem::Dependency
47
+ name: multi_json
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ~>
52
+ - !ruby/object:Gem::Version
53
+ version: '1.8'
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ~>
60
+ - !ruby/object:Gem::Version
61
+ version: '1.8'
62
+ description: ! 'Goliath Chimp
63
+
64
+
65
+ A collection of reusable Rack classes and other goodies
66
+
67
+ for use in Goliath APIs.'
68
+ email:
69
+ - travis@infochimps.com
70
+ executables: []
71
+ extensions: []
72
+ extra_rdoc_files: []
73
+ files:
74
+ - .gitignore
75
+ - .travis.yml
76
+ - Gemfile
77
+ - LICENSE.md
78
+ - README.md
79
+ - Rakefile
80
+ - goliath-chimp.gemspec
81
+ - lib/goliath/chimp.rb
82
+ - lib/goliath/chimp/handler.rb
83
+ - lib/goliath/chimp/rack/api_version.rb
84
+ - lib/goliath/chimp/rack/control_methods.rb
85
+ - lib/goliath/chimp/rack/force_content_type.rb
86
+ - lib/goliath/chimp/rack/formatters/json.rb
87
+ - lib/goliath/chimp/rack/validation/required_routes.rb
88
+ - lib/goliath/chimp/rack/validation/route_handler.rb
89
+ - lib/goliath/chimp/rack/validation/routes.rb
90
+ - lib/goliath/chimp/version.rb
91
+ - spec/handler_spec.rb
92
+ - spec/rack/api_version_spec.rb
93
+ - spec/rack/control_methods_spec.rb
94
+ - spec/rack/force_content_type_spec.rb
95
+ - spec/rack/formatters/json_spec.rb
96
+ - spec/rack/validations/required_routes_spec.rb
97
+ - spec/rack/validations/route_handler_spec.rb
98
+ - spec/rack/validations/routes_spec.rb
99
+ - spec/spec_helper.rb
100
+ homepage: https://github.com/infochimps-labs/goliath-chimp
101
+ licenses:
102
+ - Apache 2.0
103
+ post_install_message:
104
+ rdoc_options: []
105
+ require_paths:
106
+ - lib
107
+ required_ruby_version: !ruby/object:Gem::Requirement
108
+ none: false
109
+ requirements:
110
+ - - ! '>='
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ segments:
114
+ - 0
115
+ hash: -3557348802184007792
116
+ required_rubygems_version: !ruby/object:Gem::Requirement
117
+ none: false
118
+ requirements:
119
+ - - ! '>='
120
+ - !ruby/object:Gem::Version
121
+ version: '0'
122
+ segments:
123
+ - 0
124
+ hash: -3557348802184007792
125
+ requirements: []
126
+ rubyforge_project:
127
+ rubygems_version: 1.8.23
128
+ signing_key:
129
+ specification_version: 3
130
+ summary: Collection of Chimp-inspired Goliath/Rack utility classes
131
+ test_files:
132
+ - spec/handler_spec.rb
133
+ - spec/rack/api_version_spec.rb
134
+ - spec/rack/control_methods_spec.rb
135
+ - spec/rack/force_content_type_spec.rb
136
+ - spec/rack/formatters/json_spec.rb
137
+ - spec/rack/validations/required_routes_spec.rb
138
+ - spec/rack/validations/route_handler_spec.rb
139
+ - spec/rack/validations/routes_spec.rb
140
+ - spec/spec_helper.rb