grape-client-generator 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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9968c76ead0846ba188b4706c17afd05809198dc
4
+ data.tar.gz: c96515b7c46765efc59d1268d052f8a692ecb01d
5
+ SHA512:
6
+ metadata.gz: 8fcfb671ebbd2cd7182d21483af6b5cefe08d7b74d26287dd46ea8a39941f8b03312c02afe0984df218d612dc3c0c8fbc6a660be4375dc2093122d6d42115b93
7
+ data.tar.gz: 9871eb364e06eea7d1454c93417bad76efade19ba037f93e256f248be6ee583b98abab9fe12a881fe3385cd7f41d34863d23b5a2416d0743b1bd007c0737b8df
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ group :development, :test do
6
+ gem 'rake'
7
+ gem 'pry'
8
+ gem 'pry-nav'
9
+ gem 'grape'
10
+ end
11
+
12
+ group :test do
13
+ gem 'rspec', '~> 2.11.0'
14
+ gem 'rr', '~> 1.0.4'
15
+ end
@@ -0,0 +1,3 @@
1
+ == 1.0.0
2
+
3
+ * Birthday!
data/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,88 @@
1
+ grape-client-generator
2
+ ======================
3
+
4
+ Automatically generate clients for your Grape APIs.
5
+
6
+ ### Installation
7
+
8
+ Install the gem as you would any other:
9
+
10
+ ```
11
+ gem install grape-client-generator
12
+ ```
13
+
14
+ or put it in your Gemfile.
15
+
16
+ The grape-client-generator is probably best used in a Rakefile. Require it like so:
17
+
18
+ ```ruby
19
+ require 'grape/client_generator'
20
+ ```
21
+
22
+ ### Usage
23
+
24
+ Let's say we have a little Grape API that looks like this:
25
+
26
+ ```ruby
27
+ class DummyEndpoints < Grape::API
28
+
29
+ desc "I'm a little teapot."
30
+
31
+ set(:name, "dummy")
32
+
33
+ get :dummy do
34
+ puts "hello"
35
+ end
36
+
37
+ end
38
+ ```
39
+
40
+ **NOTE**: Pay special attention to the call to `set(:name, ...)` above. grape-client-generator expects all endpoints to give themselves a name that will be used as the method name in the generated class.
41
+
42
+ grape-client-generator lets you automatically generate a (Ruby) consumer for this API that could potentially be packaged up into a gem. The `RubyGenerator` class takes in an array of `Grape::API`s to process as well as a number of additional options like `:namespace`, `:class_name`, `:default_version`, and `:response_types`. Here's an example:
43
+
44
+ ```ruby
45
+ generator = Grape::ClientGenerator::Ruby::RubyGenerator.new([DummyEndpoints], {
46
+ :namespace => "MyClient",
47
+ :class_name => "Api",
48
+ :default_version => "v1",
49
+ :response_types => [:xml, :json]
50
+ })
51
+ ```
52
+
53
+ To generate the source code for your client, use the `generate_each` method:
54
+
55
+ ```ruby
56
+ generator.generate_each do |file_name, content|
57
+ File.open(File.join("./output", file_name), "w+") do |f|
58
+ f.write(content)
59
+ end
60
+ end
61
+ ```
62
+
63
+ ### Disclaimers
64
+
65
+ This gem makes quite a few assumptions about your Grape endpoints and is far from complete. For example, it expects each endpoint to have a simple path (i.e. no named arguments) and that you're placing the version in the url (eg. http://mysite.com/v1/...). Have a feature in mind you'd like to see added? Submit a pull request!
66
+
67
+ ### Requirements
68
+
69
+ You'll need to add grape-client-generator into an environment that has access to Grape, although it is not specifically listed as a dependency.
70
+
71
+ The mustache gem is used to assemble the generated Ruby source files.
72
+
73
+ If you'd like to use the `JsonResponseParser` that grape-client-generator can generate, you'll need to add one of the json gems into your environment, usually either `json` or `json-pure`.
74
+
75
+ ### Running Tests
76
+
77
+ Run `bundle exec rake` or `bundle exec rspec`.
78
+
79
+ ### Authors
80
+
81
+ * Cameron C. Dutro: https://github.com/camertron
82
+
83
+ ## Links
84
+ * grape [https://github.com/intridea/grape](https://github.com/intridea/grape)
85
+
86
+ ## License
87
+
88
+ Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1,20 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'rubygems' unless ENV['NO_RUBYGEMS']
4
+
5
+ require 'bundler'
6
+ require 'digest'
7
+
8
+ require 'rspec/core/rake_task'
9
+ require 'rubygems/package_task'
10
+
11
+ require './lib/grape/client_generator'
12
+
13
+ Bundler::GemHelper.install_tasks
14
+
15
+ task :default => :spec
16
+
17
+ desc 'Run specs'
18
+ RSpec::Core::RakeTask.new do |t|
19
+ t.pattern = './spec/**/*_spec.rb'
20
+ end
@@ -0,0 +1,22 @@
1
+ # encoding: UTF-8
2
+
3
+ $:.unshift File.join(File.dirname(__FILE__), 'lib')
4
+ require 'grape/client-generator/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "grape-client-generator"
8
+ s.version = ::Grape::ClientGenerator::VERSION
9
+ s.authors = ["Cameron Dutro"]
10
+ s.email = ["cdutro@twitter.com"]
11
+ s.homepage = ""
12
+
13
+ s.description = s.summary = "Automatically generate clients for your Grape APIs."
14
+
15
+ s.platform = Gem::Platform::RUBY
16
+ s.has_rdoc = true
17
+
18
+ s.add_dependency 'mustache'
19
+ s.require_path = 'lib'
20
+
21
+ s.files = Dir["{lib,spec}/**/*", "Gemfile", "History.txt", "LICENSE", "README.md", "Rakefile", "grape-client-generator.gemspec"]
22
+ end
@@ -0,0 +1,48 @@
1
+ # encoding: UTF-8
2
+
3
+ module Grape
4
+ module ClientGenerator
5
+
6
+ autoload :Ruby, 'grape/client-generator/ruby'
7
+
8
+ class Generator
9
+
10
+ DEFAULT_RESPONSE_TYPES = [:xml]
11
+ DEFAULT_CLASS_NAME = "Api"
12
+ DEFAULT_VERSION = "v1"
13
+
14
+ attr_reader :grape_classes, :response_types, :namespace, :default_version, :class_name
15
+
16
+ def initialize(grape_classes, options = {})
17
+ @grape_classes = grape_classes
18
+ @response_types = options[:response_types] || DEFAULT_RESPONSE_TYPES
19
+ @namespace = options[:namespace] || generate_namespace_from(grape_classes.first)
20
+ @class_name = options[:class_name] || DEFAULT_CLASS_NAME
21
+ @default_version = options[:default_version] || DEFAULT_VERSION
22
+ end
23
+
24
+ def each_endpoint
25
+ @grape_classes.each do |grape_class|
26
+ grape_class.endpoints.each do |endpoint|
27
+ yield endpoint
28
+ end
29
+ end
30
+ end
31
+
32
+ def map_endpoints
33
+ result = []
34
+ each_endpoint do |endpoint|
35
+ result << (yield endpoint)
36
+ end
37
+ result
38
+ end
39
+
40
+ protected
41
+
42
+ def generate_namespace_from(klass)
43
+ "#{klass.name.split("::").last}Client"
44
+ end
45
+
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,16 @@
1
+ # encoding: UTF-8
2
+
3
+ module Grape
4
+ module ClientGenerator
5
+ module Ruby
6
+
7
+ autoload :ClientFile, "grape/client-generator/ruby/files"
8
+ autoload :Api, "grape/client-generator/ruby/files"
9
+ autoload :XmlResponseParser, "grape/client-generator/ruby/files"
10
+ autoload :JsonResponseParser, "grape/client-generator/ruby/files"
11
+
12
+ autoload :RubyGenerator, "grape/client-generator/ruby/ruby_generator"
13
+
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,100 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'mustache'
4
+
5
+ module Grape
6
+ module ClientGenerator
7
+ module Ruby
8
+
9
+ class ClientFile
10
+ attr_reader :generator
11
+
12
+ def initialize(generator)
13
+ @generator = generator
14
+ end
15
+
16
+ def render
17
+ Mustache.template_path = mustache_path
18
+ Mustache.render(File.read(input_file), params)
19
+ end
20
+
21
+ def input_file
22
+ raise NotImplementedError
23
+ end
24
+
25
+ def output_file_name
26
+ raise NotImplementedError
27
+ end
28
+
29
+ def params
30
+ raise NotImplementedError
31
+ end
32
+
33
+ protected
34
+
35
+ def mustache_file_for(name)
36
+ File.join(mustache_path, "#{name}.mustache")
37
+ end
38
+
39
+ def mustache_path
40
+ File.join(File.dirname(__FILE__), "mustache")
41
+ end
42
+ end
43
+
44
+ class Api < ClientFile
45
+ def output_file_name
46
+ "api.rb"
47
+ end
48
+
49
+ def input_file
50
+ mustache_file_for("api")
51
+ end
52
+
53
+ def params
54
+ {
55
+ :namespace => generator.namespace,
56
+ :class_name => generator.class_name,
57
+ :default_version => generator.default_version,
58
+ :default_format => generator.response_types.first,
59
+ :endpoints => generator.map_endpoints do |endpoint|
60
+ {
61
+ :path => endpoint.options[:path].first.to_s,
62
+ :name => endpoint.settings[:name], # expected to be set by all endpoints
63
+ :verb => endpoint.options[:method].first.downcase
64
+ }
65
+ end
66
+ }
67
+ end
68
+ end
69
+
70
+ class XmlResponseParser < ClientFile
71
+ def output_file_name
72
+ "xml_response_parser.rb"
73
+ end
74
+
75
+ def input_file
76
+ mustache_file_for("xml_response_parser")
77
+ end
78
+
79
+ def params
80
+ { :namespace => generator.namespace }
81
+ end
82
+ end
83
+
84
+ class JsonResponseParser < ClientFile
85
+ def output_file_name
86
+ "json_response_parser.rb"
87
+ end
88
+
89
+ def input_file
90
+ mustache_file_for("json_response_parser")
91
+ end
92
+
93
+ def params
94
+ { :namespace => generator.namespace }
95
+ end
96
+ end
97
+
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,83 @@
1
+ # encoding: UTF-8
2
+
3
+ {{> warning_message}}
4
+
5
+ require 'net/http'
6
+ require 'cgi'
7
+
8
+ module {{namespace}}
9
+ class {{class_name}}
10
+
11
+ attr_reader :base_url, :version, :format
12
+
13
+ def initialize(base_url, options = {})
14
+ @base_url = base_url
15
+ @version = options[:version] || "{{default_version}}"
16
+ @format = options[:format] || "{{default_format}}"
17
+ end
18
+
19
+ {{#endpoints}}
20
+ def {{name}}(params = {})
21
+ make_request("{{verb}}", "{{path}}", params)
22
+ end
23
+
24
+ {{/endpoints}}
25
+ private
26
+
27
+ def make_request(verb, path, params)
28
+ parse_response(
29
+ case verb
30
+ when "post"
31
+ url = make_post_url(path)
32
+ post(url, params)
33
+ when "get"
34
+ url = make_get_url(path, params)
35
+ get(url)
36
+ else
37
+ raise "Unsupported HTTP verb."
38
+ end
39
+ )
40
+ end
41
+
42
+ def parse_response(response)
43
+ send(:"parse_#{format}_response", response)
44
+ end
45
+
46
+ def parse_xml_response(response)
47
+ XmlResponseParser.parse(response)
48
+ end
49
+
50
+ def parse_json_response(response)
51
+ JsonResponseParser.parse(response)
52
+ end
53
+
54
+ def make_param_string(params)
55
+ (params.map do |key, val|
56
+ "#{CGI.escape(key.to_s)}=#{CGI.escape(val.to_s)}"
57
+ end).join("&")
58
+ end
59
+
60
+ def make_get_url(path, params)
61
+ File.join(base_url, version, "#{path}.#{format}", "?#{make_param_string(params)}")
62
+ end
63
+
64
+ def make_post_url(path)
65
+ File.join(base_url, version, "#{path}.#{format}")
66
+ end
67
+
68
+ def post(url, params)
69
+ uri = URI.parse(url)
70
+ http = Net::HTTP.new(uri.host, uri.port)
71
+ request = Net::HTTP::Post.new(uri.path)
72
+ request.body = make_param_string(params)
73
+ resp = http.request(request)
74
+ resp.body
75
+ end
76
+
77
+ def get(url)
78
+ resp = Net::HTTP.get_response(URI.parse(url))
79
+ resp.body
80
+ end
81
+
82
+ end
83
+ end
@@ -0,0 +1,18 @@
1
+ # encoding: UTF-8
2
+
3
+ {{> warning_message}}
4
+
5
+ # only require this file if you have the json gem available
6
+ require "json"
7
+
8
+ module {{namespace}}
9
+ class JsonResponseParser
10
+
11
+ class << self
12
+ def parse(json_text)
13
+ JSON.parse(json_text)
14
+ end
15
+ end
16
+
17
+ end
18
+ end
@@ -0,0 +1,3 @@
1
+ # NOTICE:
2
+ # * This file was generated by the grape-client-generator gem. Changes may be lost on regeneration.
3
+ # * http://github.com/camertron/grape-client-generator
@@ -0,0 +1,71 @@
1
+ # encoding: UTF-8
2
+
3
+ {{> warning_message}}
4
+
5
+ require "rexml/document"
6
+
7
+ module {{namespace}}
8
+ class XmlResponseParser
9
+
10
+ class << self
11
+ def parse(xml_text)
12
+ doc = REXML::Document.new(xml_text)
13
+ name = doc.root.name == "error" ? "error" : "response"
14
+ { name => parse_element(doc.root) }
15
+ end
16
+
17
+ private
18
+
19
+ def parse_element(element)
20
+ case element
21
+ when REXML::Element
22
+ recursive_types = ["hash", "array"]
23
+ index = recursive_types.index(element.name)
24
+ index ||= recursive_types.index(element.attributes["type"])
25
+
26
+ if index
27
+ send(:"parse_#{recursive_types[index]}", element)
28
+ else
29
+ if element.children.any? { |child| child.is_a?(REXML::Element) }
30
+ parse_hash(element)
31
+ else
32
+ element.text
33
+ end
34
+ end
35
+ when REXML::Text
36
+ element.value
37
+ end
38
+ end
39
+
40
+ def parse_hash(element)
41
+ element.children.inject({}) do |ret, child|
42
+ if child.is_a?(REXML::Element)
43
+ key = format_key(child.name)
44
+ ret[key] = hash_attributes(child.attributes).merge({
45
+ "value" => parse_element(child)
46
+ })
47
+ end
48
+
49
+ ret
50
+ end
51
+ end
52
+
53
+ def hash_attributes(attrs)
54
+ attrs.inject({}) { |ret, arr| ret[format_key(arr[0])] = arr[1]; ret }
55
+ end
56
+
57
+ def format_key(key)
58
+ key.gsub("-", "_")
59
+ end
60
+
61
+ def parse_array(element)
62
+ element.children.map do |child|
63
+ if child.is_a?(REXML::Element)
64
+ parse_element(child)
65
+ end
66
+ end.compact
67
+ end
68
+ end
69
+
70
+ end
71
+ end
@@ -0,0 +1,27 @@
1
+ # encoding: UTF-8
2
+
3
+ module Grape
4
+ module ClientGenerator
5
+ module Ruby
6
+
7
+ class RubyGenerator < Generator
8
+ def generate_each
9
+ client_file_classes.each do |klass|
10
+ client_file = klass.new(self)
11
+ yield client_file.output_file_name, client_file.render
12
+ end
13
+ end
14
+
15
+ protected
16
+
17
+ def client_file_classes
18
+ list = [Api]
19
+ list << XmlResponseParser if response_types.include?(:xml)
20
+ list << JsonResponseParser if response_types.include?(:json)
21
+ list
22
+ end
23
+ end
24
+
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,7 @@
1
+ # encoding: UTF-8
2
+
3
+ module Grape
4
+ module ClientGenerator
5
+ VERSION = "1.0.0"
6
+ end
7
+ end
@@ -0,0 +1,4 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'grape/client-generator/version'
4
+ require 'grape/client-generator/generator'
@@ -0,0 +1,60 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'spec_helper'
4
+
5
+ include Grape::ClientGenerator
6
+
7
+ describe Generator do
8
+ describe "#initialize" do
9
+ it "should use sensible defaults" do
10
+ Generator.new([DummyEndpoints]).tap do |gen|
11
+ gen.grape_classes.should == [DummyEndpoints]
12
+ gen.response_types.should == [:xml]
13
+ gen.namespace.should == "DummyEndpointsClient"
14
+ gen.class_name.should == "Api"
15
+ gen.default_version.should == "v1"
16
+ end
17
+ end
18
+
19
+ it "should allow the defaults to be overridden" do
20
+ gen = Generator.new([DummyEndpoints], {
21
+ :response_types => [:json],
22
+ :namespace => "Blarg",
23
+ :class_name => "Hello",
24
+ :default_version => "8"
25
+ })
26
+
27
+ gen.grape_classes.should == [DummyEndpoints]
28
+ gen.response_types.should == [:json]
29
+ gen.namespace.should == "Blarg"
30
+ gen.class_name.should == "Hello"
31
+ gen.default_version.should == "8"
32
+ end
33
+ end
34
+
35
+ context "with a generator" do
36
+ before(:each) do
37
+ @generator = Generator.new([DummyEndpoints])
38
+ end
39
+
40
+ describe "#each_endpoint" do
41
+ it "iterates over each endpoint" do
42
+ endpoints = []
43
+ @generator.each_endpoint do |endpoint|
44
+ endpoint.should be_a(Grape::Endpoint)
45
+ endpoints << endpoint.settings[:name]
46
+ end
47
+ endpoints.should == ["kirk", "shaggy"]
48
+ end
49
+ end
50
+
51
+ describe "#map_endpoints" do
52
+ it "returns an array of mapped values for the endpoints" do
53
+ @generator.map_endpoints do |endpoint|
54
+ endpoint.should be_a(Grape::Endpoint)
55
+ endpoint.settings[:name]
56
+ end.should == ["kirk", "shaggy"]
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,52 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'spec_helper'
4
+
5
+ include Grape::ClientGenerator
6
+ include Grape::ClientGenerator::Ruby
7
+
8
+ describe Api do
9
+ describe "#render" do
10
+ it "wraps the code in a module and a class with the given names" do
11
+ generator = Generator.new([DummyEndpoints], {
12
+ :namespace => "AwesomeClient",
13
+ :class_name => "GreatApi"
14
+ })
15
+
16
+ Api.new(generator).render.tap do |code|
17
+ code.should match(/module AwesomeClient/)
18
+ code.should match(/class GreatApi/)
19
+ end
20
+ end
21
+
22
+ it "renders a Ruby method for each endpoint with the correct HTTP verb" do
23
+ generator = Generator.new([DummyEndpoints])
24
+ Api.new(generator).render.tap do |code|
25
+ code.should match(/def kirk.*\n\s*make_request\("get"/)
26
+ code.should match(/def shaggy.*\n\s*make_request\("post"/)
27
+ end
28
+ end
29
+ end
30
+ end
31
+
32
+ describe XmlResponseParser do
33
+ describe "#render" do
34
+ it "wraps the code in the right module namespace" do
35
+ generator = Generator.new([DummyEndpoints], :namespace => "AwesomeClient")
36
+ XmlResponseParser.new(generator).render.tap do |code|
37
+ code.should match(/module AwesomeClient/)
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ describe JsonResponseParser do
44
+ describe "#render" do
45
+ it "wraps the code in the right module namespace" do
46
+ generator = Generator.new([DummyEndpoints], :namespace => "AwesomeClient")
47
+ JsonResponseParser.new(generator).render.tap do |code|
48
+ code.should match(/module AwesomeClient/)
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,170 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'spec_helper'
4
+
5
+ include Grape::ClientGenerator::Ruby
6
+
7
+ describe RubyGenerator do
8
+ describe "#generate_each" do
9
+ it "generates the right files" do
10
+ generator = RubyGenerator.new([DummyEndpoints], {
11
+ :response_types => [:xml, :json]
12
+ })
13
+
14
+ file_names = []
15
+ generator.generate_each { |file_name, contents| file_names << file_name }
16
+ file_names.should == [
17
+ "api.rb",
18
+ "xml_response_parser.rb",
19
+ "json_response_parser.rb"
20
+ ]
21
+ end
22
+ end
23
+
24
+ describe "generated classes" do
25
+ before(:all) do
26
+ generator = RubyGenerator.new([DummyEndpoints], {
27
+ :response_types => [:xml, :json],
28
+ :namespace => "MyClient",
29
+ :default_format => "xml",
30
+ :default_version => "v1"
31
+ })
32
+
33
+ @api_module = Module.new do
34
+ generator.generate_each do |file_name, contents|
35
+ class_eval(contents)
36
+ end
37
+ end
38
+ end
39
+
40
+ it "defines the correct classes" do
41
+ @api_module.constants.should include(:MyClient)
42
+
43
+ [:Api, :XmlResponseParser, :JsonResponseParser].each do |const_sym|
44
+ @api_module::MyClient.constants.should include(const_sym)
45
+ end
46
+ end
47
+
48
+ describe "generated api class" do
49
+ let(:generic_xml_http_response) do
50
+ Class.new do
51
+ def body
52
+ "<some-xml-response></some-xml-response>"
53
+ end
54
+ end.new
55
+ end
56
+
57
+ before(:each) do
58
+ @api = @api_module::MyClient::Api.new("http://twitter.com")
59
+ end
60
+
61
+ it "properly fires off a get request" do
62
+ expected_uri = URI.parse("http://twitter.com/v1/kirk.xml/?foo=bar&juicy=kale")
63
+ mock(Net::HTTP).get_response(expected_uri) { generic_xml_http_response }
64
+
65
+ @api.kirk(
66
+ :foo => "bar",
67
+ :juicy => "kale"
68
+ )
69
+ end
70
+
71
+ it "properly fires off a post request" do
72
+ expected_uri = URI.parse("http://twitter.com/v1/shaggy.xml")
73
+
74
+ any_instance_of(Net::HTTP) do |http|
75
+ mock(http).request(anything) do |req|
76
+ # we have to assume the host is correct since net/http won't give it to us in this context
77
+ req.path.should == "/v1/shaggy.xml"
78
+ req.body.should == "foo=bar&juicy=kale"
79
+
80
+ generic_xml_http_response
81
+ end
82
+ end
83
+
84
+ @api.shaggy(
85
+ :foo => "bar",
86
+ :juicy => "kale"
87
+ )
88
+ end
89
+ end
90
+
91
+ describe "generated json response parser class" do
92
+ let(:parser) { @api_module::MyClient::JsonResponseParser }
93
+
94
+ describe("#parse") do
95
+ it "parses a json response successfully" do
96
+ parser.parse('{"hello": "world"}').should == { "hello" => "world" }
97
+ end
98
+ end
99
+ end
100
+
101
+ describe "generated xml response parser class" do
102
+ let(:parser) { @api_module::MyClient::XmlResponseParser }
103
+
104
+ describe("#parse") do
105
+ it "uses 'error' as the root if given an error-ish response" do
106
+ response = %q(<error><message>jelly beans</message></error>)
107
+ parser.parse(response).should == {
108
+ "error" => {
109
+ "message" => {
110
+ "value" => "jelly beans"
111
+ }
112
+ }
113
+ }
114
+ end
115
+
116
+ it "handles a single-element hash response" do
117
+ response = %q(<hash><dumbledore>wizard</dumbledore></hash>)
118
+ parser.parse(response).should == {
119
+ "response" => {
120
+ "dumbledore" => {
121
+ "value" => "wizard"
122
+ }
123
+ }
124
+ }
125
+ end
126
+
127
+ it "handles an array response" do
128
+ response = %q(<strings type="array">)
129
+ response += %q(<string>gryffindor</string><string>hufflepuff</string>)
130
+ response += %q(<string>ravenclaw</string><string>slytherin</string>)
131
+ response += %q(</strings>)
132
+
133
+ parser.parse(response).should == {
134
+ "response" => ["gryffindor", "hufflepuff", "ravenclaw", "slytherin"]
135
+ }
136
+ end
137
+
138
+ it "handles a nested hash and array combination" do
139
+ response = %q(<hash>) +
140
+ %q(<houses type="array">) +
141
+ %q(<house>gryffindor</house>) +
142
+ %q(<house>hufflepuff</house>) +
143
+ %q(<house>ravenclaw</house>) +
144
+ %q(<house>slytherin</house>) +
145
+ %q(</houses>) +
146
+ %q(<friends type="array">) +
147
+ %q(<friend>moony</friend>) +
148
+ %q(<friend>wormtail</friend>) +
149
+ %q(<friend>padfoot</friend>) +
150
+ %q(<friend>prongs</friend>) +
151
+ %q(</friends>) +
152
+ %q(</hash>)
153
+
154
+ parser.parse(response).should == {
155
+ "response" => {
156
+ "houses" => {
157
+ "type" => "array",
158
+ "value" => ["gryffindor", "hufflepuff", "ravenclaw", "slytherin"]
159
+ },
160
+ "friends" => {
161
+ "type" => "array",
162
+ "value" => ["moony", "wormtail", "padfoot", "prongs"]
163
+ }
164
+ }
165
+ }
166
+ end
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,27 @@
1
+ # encoding: UTF-8
2
+
3
+ require 'rspec'
4
+ require 'grape'
5
+ require 'grape/client_generator'
6
+
7
+ RSpec.configure do |config|
8
+ config.mock_with :rr
9
+ end
10
+
11
+ class DummyEndpoints < Grape::API
12
+
13
+ desc "I'm a little teapot."
14
+
15
+ set(:name, "kirk")
16
+
17
+ get :kirk do
18
+ puts "spock"
19
+ end
20
+
21
+ set(:name, "shaggy")
22
+
23
+ post :shaggy do
24
+ puts "scooby"
25
+ end
26
+
27
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: grape-client-generator
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Cameron Dutro
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-06-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: mustache
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: Automatically generate clients for your Grape APIs.
28
+ email:
29
+ - cdutro@twitter.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - lib/grape/client-generator/generator.rb
35
+ - lib/grape/client-generator/ruby/files.rb
36
+ - lib/grape/client-generator/ruby/mustache/api.mustache
37
+ - lib/grape/client-generator/ruby/mustache/json_response_parser.mustache
38
+ - lib/grape/client-generator/ruby/mustache/warning_message.mustache
39
+ - lib/grape/client-generator/ruby/mustache/xml_response_parser.mustache
40
+ - lib/grape/client-generator/ruby/ruby_generator.rb
41
+ - lib/grape/client-generator/ruby.rb
42
+ - lib/grape/client-generator/version.rb
43
+ - lib/grape/client_generator.rb
44
+ - spec/generator_spec.rb
45
+ - spec/ruby/files_spec.rb
46
+ - spec/ruby/ruby_generator_spec.rb
47
+ - spec/spec_helper.rb
48
+ - Gemfile
49
+ - History.txt
50
+ - LICENSE
51
+ - README.md
52
+ - Rakefile
53
+ - grape-client-generator.gemspec
54
+ homepage: ''
55
+ licenses: []
56
+ metadata: {}
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - '>='
64
+ - !ruby/object:Gem::Version
65
+ version: '0'
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - '>='
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubyforge_project:
73
+ rubygems_version: 2.0.3
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Automatically generate clients for your Grape APIs.
77
+ test_files: []