Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 397 lines (282 sloc) 17.776 kB
3f957e4 @Sutto Add Gemnasium status
authored
1 # RocketPants! [![Build Status](https://secure.travis-ci.org/filtersquad/rocket_pants.png?branch=master)](http://travis-ci.org/filtersquad/rocket_pants) [![Dependency Status](https://gemnasium.com/filtersquad/rocket_pants.png)](https://gemnasium.com/filtersquad/rocket_pants)
2
22b6142 @Sutto More readme tweaks.
authored
3 ## Introduction
4
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
5 First thing's first, you're probably asking yourself - "Why the ridiculous name?". It's simple, really - RocketPants is memorable, and sounds completely bad ass. - everything a library needs.
98d2351 @Sutto README work and License tweaks
authored
6
5e788d8 @levibuzolic Fixed typo in README
levibuzolic authored
7 At its core, RocketPants is a set of tools (built around existing toolsets such as ActionPack) to make it easier to build well-designed APIs in Ruby and more importantly, along side Rails. You can think of it like [Grape](https://github.com/intridea/grape), a fantastic library which RocketPants was originally inspired by but with deeper Rails and ActionPack integration.
98d2351 @Sutto README work and License tweaks
authored
8
9 ## Key Features
10
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
11 Why use RocketPants over alternatives like Grape or normal Rails? The reasons we built it come down to a couple of simple things:
98d2351 @Sutto README work and License tweaks
authored
12
13 1. **It's opinionated** (like Grape) - In this case, we dictate a certain JSON structure we've found nice to work with (after having worked with and investigated a large number of other apis), it makes it simple to add metadata along side requests and the like.
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
14 2. **Simple and Often Automatic Response Metadata** - RocketPants automatically takes care of sending metadata about paginated responses and arrays where possible. This means as a user, you only need to worry about writing `expose object_or_presenter` in your controller and RocketPants will do it's best to send as much information back to the user.
15 3. **Extended Error Support** - RocketPants has a built in framework to manage errors it knows how to handle (in the forms of mapping exceptions to a well defined JSON structure) as well as tools to make it simple to hook up to Airbrake and do things such as including an error identifier in the response.
16 4. **It's built on ActionPack** - One of the key differentiators to Grape is that RocketPants embraces ActionPack and uses the modular components included from Rails 3.0 onwards to provide things you're familiar with already such as filters.
17 5. **Semi-efficient Caching Support** - Thanks to a combination of Rails middleware and collection vs. resource distinctions, RocketPants makes it relatively easy to implement "Efficient Validation" (See [here](http://rtomayko.github.com/rack-cache/faq)). As a developer, this means you get even more benefits of http caching where possible, without the need to generate full requests when etags are present.
0222651 @Sutto Add client examples
authored
18 6. **Simple tools to consume RocketPants apis** - RocketPants includes the `RocketPants::Client` class which builds upon [APISmith](https://github.com/filtersquad/api_smith) to make it easier to build clients e.g. automatically converting paginated responses back.
98d2351 @Sutto README work and License tweaks
authored
19
22b6142 @Sutto More readme tweaks.
authored
20 ## Examples
21
22 ### A full example application
74b4567 @Sutto Add link to example app (not yet there)
authored
23
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
24 Learn better by reading code? There is also have an example app mixing models and api clients over at [Sutto/transperth-api](https://github.com/Sutto/transperth-api) that is built using RocketPants.
74b4567 @Sutto Add link to example app (not yet there)
authored
25
0222651 @Sutto Add client examples
authored
26 ### Example Server Code
22b6142 @Sutto More readme tweaks.
authored
27
7a362ce @Sutto More tweaks! Namely to the README
authored
28 Say, for example, you have a basic Food model:
22b6142 @Sutto More readme tweaks.
authored
29
30 ```ruby
7a362ce @Sutto More tweaks! Namely to the README
authored
31 class Food < ActiveRecord::Base
32 include RocketPants::Cacheable
33 end
34 ```
35
36 ```ruby
37 class FoodsController < RocketPants::Base
38
39 version 1
40
41 # The list of foods is paginated for 5 minutes, the food itself is cached
42 # until it's modified (using Efficient Validation)
43 caches :index, :show, :caches_for => 5.minutes
22b6142 @Sutto More readme tweaks.
authored
44
45 def index
7a362ce @Sutto More tweaks! Namely to the README
authored
46 expose Food.paginate(:page => params[:page])
22b6142 @Sutto More readme tweaks.
authored
47 end
48
49 def show
7a362ce @Sutto More tweaks! Namely to the README
authored
50 expose Food.find(params[:id])
22b6142 @Sutto More readme tweaks.
authored
51 end
52
53 end
54 ```
55
56 And in the router we'd just use the normal REST-like routes in Rails:
57
58 ```ruby
7a362ce @Sutto More tweaks! Namely to the README
authored
59 api :version => 1 do
60 resources :foods, :only => [:index, :show]
61 end
62 ```
63
d6092e9 @Sutto We need the version in the URL
authored
64 And then, using this example, hitting `GET http://localhost:3000/1/foods` would result in:
7a362ce @Sutto More tweaks! Namely to the README
authored
65
66 ```json
67 {
68 "response": [{
69 "id": 1,
70 "name": "Delicious Food"
71 }, {
72 "id": 2,
73 "name": "More Delicious Food"
74 }],
75 "count": 2,
76 "pagination": {
77 "previous": nil,
78 "next": nil,
79 "current": 1,
80 "per_page": 10,
81 "count": 2,
82 "pages": 1
83 }
84 }
22b6142 @Sutto More readme tweaks.
authored
85 ```
86
d6092e9 @Sutto We need the version in the URL
authored
87 with the `Cache-Control` header set whilst hitting `GET http://localhost:3000/1/foods/1` would return:
7a362ce @Sutto More tweaks! Namely to the README
authored
88
89 ```json
90 {
91 "response": {
92 "id": 1,
93 "name": "Delicious Food"
94 }
95 }
96 ```
97
98 with the `Etag` header set.
99
0222651 @Sutto Add client examples
authored
100 ### Example Client Code
101
102 Using the example above, we could then use the following to write a client:
103
104 ```ruby
105 class FoodsClient < RocketPants::Client
106
107 version 1
108 base_uri 'http://localhost:3000'
109
110 class Food < APISmith::Smash
111 property :id
112 property :name
113 end
114
115 def foods
116 get 'foods', :transformer => Food
117 end
118
119 def food(id)
120 get "foods/#{id}", :transformer => Food
121 end
122
123 end
124 ```
125
98d2351 @Sutto README work and License tweaks
authored
126 ## General Structure
127
128 RocketPants builds upon the mixin-based approach to ActionController-based rails applications that Rails 3 made possible. Instead of including everything like Rails does in `ActionController::Base`, RocketPants only includes the bare minimum to make apis. In the near future, it may be modified to work with `ActionController::Base` for the purposes of better compatibility with other gems.
129
130 Out of the box, we use the following ActionController components:
131
132 * `ActionController::HideActions` - Lets you hide methods from actions.
133 * `ActionController::UrlFor` - `url_for` helpers / tweaks by Rails to make integration with routes work better.
134 * `ActionController::Redirecting` - Allows you to use `redirect_to`.
135 * `ActionController::ConditionalGet` - Adds support for Rails caching controls, e.g. `fresh_when` and `expires_in`.
136 * `ActionController::RackDelegation` - Lets you reset the session and set the response body.
137 * `ActionController::RecordIdentifier` - Gives `dom_class` and `dom_id` methods, used for polymorphic routing.
138 * `ActionController::MimeResponds` - Gives `respond_to` with mime type controls.
139 * `AbstractController::Callbacks` - Adds support for callbacks / filters.
140 * `ActionController::Rescue` - Lets you use `rescue_from`.
141
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
142 And added our own:
98d2351 @Sutto README work and License tweaks
authored
143
144 * `RocketPants::UrlFor` - Automatically includes the current version when generating URLs from the controller.
145 * `RocketPants::Respondable` - The core of RocketPants, the code that handles converting objects to the different container types.
146 * `RocketPants::Versioning` - Allows versioning requirements on the controller to ensure it is only callable with a specific api version.
147 * `RocketPants::Instrumentation` - Adds Instrumentation notifications making it easy to use and hook into with Rails.
148 * `RocketPants::Caching` - Implements time-based caching for index actions and etag-based efficient validation for singular resources.
149 * `RocketPants::ErrorHandling` - Short hand to create errors as well as simplifications to catch and render a standardised error representation.
150 * `RocketPants::Rescuable` - Allows you to hook in to rescuing exceptions and to make it easy to post notifications to tools such as AirBrake.
151
152 To use RocketPants, instead of inheriting from `ActionController::Base`, just inherit from `RocketPants::Base`.
153
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
154 Likewise, in Rails applications RocketPants also adds `RocketPants::CacheMiddleware` before the controller endpoints to implement ["Efficient Validation"](http://rtomayko.github.com/rack-cache/faq).
98d2351 @Sutto README work and License tweaks
authored
155
149db46 @Sutto More README docs / tweaks
authored
156 ## Installing RocketPants
157
158 Installing RocketPants is a simple matter of adding:
159
160 gem 'rocket_pants', '~> 1.0'
161
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
162 To your `Gemfile` and running `bundle install`. Next, instead of inherited from `ActionController::Base`, simply inherit from `RocketPants::Base` instead. If you're working with an API-only application, I typically change this in `ApplicationController` and inherit from `ApplicationController` as usual. Otherwise, I generate a new `ApiController` base controller along side `ApplicationController` which instead inherits from `RocketPants::Base` and place all my logic there.
149db46 @Sutto More README docs / tweaks
authored
163
164 ## Configuration
165
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
166 Setting up RocketPants in your rails application is pretty simple and requires a minimal amount of effort. Inside your environment configuration, RocketPants offers the following options to control how it's configured (and their expanded alternatives):
149db46 @Sutto More README docs / tweaks
authored
167
168 - `config.rocket_pants.use_caching` - Defaulting to true for production environments and false elsewhere, defines whether RocketPants caching setup as described below is used.
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
169 - `config.rocket_pants.cache` - A `Moneta::Store` instance used as the RocketPants cache, defaulting to a moneta memory instance. Change for proper caching. (See [here](https://github.com/wycats/moneta) for more information on Moneta.)
149db46 @Sutto More README docs / tweaks
authored
170
171 ## Version Controllers / Routes
172
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
173 The current preferred way of dealing with version APIs in RocketPants is to do it using routes in the form of `/:version/:endpoint` - e.g. `GET /1/users/324`. RocketPants has support in the router and controller level for enforcing and controlling this. In the controller, it's a matter of specifying the required API versions:
149db46 @Sutto More README docs / tweaks
authored
174
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
175 ```ruby
176 class UsersController < RocketPants::Base
177 version 1 # A single version
178 # or...
179 version 2..3 # 2-3 support this controller
180 end
181 ```
149db46 @Sutto More README docs / tweaks
authored
182
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
183 And in the case of multiple versions, I strongly encourage namespaces the controllers inside modules. If the version param (as specified) by the URL does not match, then the specified controller will return an `:invalid_version` error as shown below.
149db46 @Sutto More README docs / tweaks
authored
184
185 Next, in your `config/routes.rb` file, you can also declare versions using the following syntax and it will automatically set up the routes for you:
186
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
187 ```ruby
188 api :version => 1 do
189 get 'x', :to => 'test#item'
190 end
191 ```
149db46 @Sutto More README docs / tweaks
authored
192
193 Which will route `GET /1/x` to `TestController#item`.
194
195 Likewise, you can specify a route for multiple versions by:
196
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
197 ```ruby
198 api :versions => 1..3 do
199 get 'x', :to => 'test#item'
200 end
201 ```
149db46 @Sutto More README docs / tweaks
authored
202
98d2351 @Sutto README work and License tweaks
authored
203 ## Working with data
204
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
205 When using RocketPants, you write your controllers the same as how you would with normal ActionController, the only thing that changes is how you handle data. `head` and `redirect_to` still work exactly the same as in Rails, but instead of using `respond_with` and `render` you instead use RocketPant's `exposes` methods (and it's kind). Namely:
3f8d609 @Sutto More type conversion docs
authored
206
207 - `expose` / `exposes` - The core of all type conversion, will check the type of data and automatically convert it to the correct time (for either a singular, collection or paginated resource).
208 - `paginated` - Render an object as a paginated collection of data.
209 - `collection` - Renders a collection of objects - e.g. an array of users.
210 - `resource` - Renders a single object.
211
212 Along side the above that wrap data, it also provides:
213
214 - `responds` - Renders JSON, normalizing the object first (unwrapped).
215 - `render_json` - Renders an object as JSON.
216
217 ### Singular Resources
218
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
219 Singular resources will be converted to JSON via `serializable_hash`, passing through any objects
3f8d609 @Sutto More type conversion docs
authored
220 and then wrapped in an object as the `response` key:
221
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
222 ```json
223 {
224 "response": {
225 "your": "serialized-object"
226 }
227 }
228 ```
3f8d609 @Sutto More type conversion docs
authored
229
230 ### Collections
231
232 Similar to singular resources, but also include extra data about the count of items.
233
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
234 ```json
235 {
236 "response": [{
237 "name": "object-one"
238 }, {
239 "name": "object-two"
240 }],
241 "count": 2
242 }
243 ```
3f8d609 @Sutto More type conversion docs
authored
244
245 ### Paginated Collections
246
247 The final type, similar to paginated objects but it includes details about the paginated data:
248
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
249 ```json
250 {
251 "response": [
252 {"name": "object-one"},
253 {"name": "object-two"},
254 {"name": "object-three"},
255 {"name": "object-four"},
256 {"name": "object-five"}
257 ],
258 "count": 5,
259 "pagination": {
260 "previous": 1,
261 "next": 3,
262 "current": 2,
263 "per_page": 5,
1e498dc @levibuzolic Missing comma in paginated collections example
levibuzolic authored
264 "count": 23,
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
265 "pages": 5
266 }
267 }
268 ```
98d2351 @Sutto README work and License tweaks
authored
269
270 ## Registering / Dealing with Errors
271
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
272 One of the built in features of RocketPants is the ability to handle rescuing / controlling exceptions and more importantly to handle mapping exceptions to names, messages and error codes.
4da07ec @Sutto Started writing docs on the error handling
authored
273
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
274 This comes in useful when you wish to automatically convert exceptions such as `ActiveRecord::RecordNotFound` to a structured bit of data in the response. Namely, it makes it trivial to generate objects that follow the JSON structure of:
4da07ec @Sutto Started writing docs on the error handling
authored
275
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
276 ```json
277 {
278 "error": "standard_error_name",
279 "error_description": "A translated error message describing what happened."
280 }
281 ```
4da07ec @Sutto Started writing docs on the error handling
authored
282
283 It also adds a facilities to make it easy to add extra information to the response.
284
285 RocketPants will also attempt to convert all errors in the controller, defaulting to the `"system"` exception name and message as the error description. We also provide a registry to allow throwing exception from their symbolic name like so:
286
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
287 ```ruby
288 error! :not_found
289 ```
4da07ec @Sutto Started writing docs on the error handling
authored
290
291 In the controller.
292
293 Out of the box, the following exceptions come pre-registered and setup:
294
295 - `:throttled` - The user has hit an api throttled error.
296 - `:unauthenticated` - The user doesn't have valid authentication details.
297 - `:invalid_version` - An invalid API version was specified.
298 - `:not_implemented` - The specified endpoint is not yet implemented.
299 - `:not_found` - The given resource could not be found.
300
98d2351 @Sutto README work and License tweaks
authored
301 ## Implementing Efficient Validation
302
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
303 One of the core design principles built into RocketPants is simple support for "Efficient Validation" as described in the [Rack::Cache FAQ](http://rtomayko.github.com/rack-cache/faq) - Namely, it adds simple support for object-level caching using etags with fast verification thanks to the `RocketPants::CacheMiddleware` cache middleware.
149db46 @Sutto More README docs / tweaks
authored
304
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
305 To do this, it uses `RocketPants.cache`, by default any Moneta-based store, to keep a mapping of object -> current cache key. RocketPants will then generate the etag when caching is enabled in the controller for singular-responses, generating an etag that can be quickly validated.
149db46 @Sutto More README docs / tweaks
authored
306
307 For example, you'd add the following to your model:
308
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
309 ```ruby
310 class User < ActiveRecord::Base
311 include RocketPants::Cacheable
312 end
313 ```
149db46 @Sutto More README docs / tweaks
authored
314
315 And then in your controller, you'd have something like:
316
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
317 ```ruby
318 class UsersController < RocketPants::Base
149db46 @Sutto More README docs / tweaks
authored
319
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
320 version 1
149db46 @Sutto More README docs / tweaks
authored
321
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
322 # Time based, e.g. collections, will be cached for 5 minutes - whilst singular
323 # items e.g. show will use etag-based caching:
324 caches :show, :index, :caches_for => 5.minutes
149db46 @Sutto More README docs / tweaks
authored
325
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
326 def index
327 expose User.all
328 end
149db46 @Sutto More README docs / tweaks
authored
329
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
330 def show
331 expose User.find(params[:id])
332 end
149db46 @Sutto More README docs / tweaks
authored
333
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
334 end
335 ```
149db46 @Sutto More README docs / tweaks
authored
336
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
337 When the user hits the index endpoint, it will generate an expiry-based caching header that caches the result for up to 5 minutes. When the user instead hits the show endpoint, it will generate a special etag that contains and object identifier portion and an object cache key. Inside `RocketPants.cache`, we store the mapping and then inside `RocketPants::CacheMiddleware`, we simply check if the given cache key matches the specified object identifier. If it does, we return a not modified response otherwise we pass it through to controller - giving the advantage of efficient caching without having to hit the full database on every request.
98d2351 @Sutto README work and License tweaks
authored
338
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
339 ## Using with RSpec
73b2f4e Add misc. test helpers
Darcy Laycock authored
340
f0a3bbd @Sutto Update README.md to mention needing the version parameters in specs. …
authored
341 When testing controllers written using RocketPants, your normal rails approach should work.
342 The only difference one needs to take into the account is the need to specify the `:version`
343 parameter on any http requests, e.g:
344
345 ```ruby
346 get :index, :version => 1
347 ```
348
349 Otherwise it will raise an exception.
350
98d2351 @Sutto README work and License tweaks
authored
351 RocketPants includes a set of helpers to make testing controllers built on `RocketPants::Base` simpler.
352
19b8bc5 @Sutto RSpec integration docs
authored
353 * `be_singular_resource` - Checks the response is a single resource - e.g. `response.should be_siingular_resource`.
354 * `be_collection_resource` - Checks the response is collection of resources - e.g. `response.should be_collection_resource`.
355 * `be_paginated_response` - Checks the response is paginated - e.g. `response.should be_paginated_response`.
356 * `be_api_error(type = any)` - Checks it returned an error for the specified exception (or check the response is an error without any argument) - e.g. `response.should be_api_error RocketPants::NotFound`.
357 * `have_exposed(data, options = {})` - Given an object and conversion options, lets you check the output exposed the same object. e.g: `response.should have_exposed user`
358
359 Likewise, it adds the following helper methods:
360
361 - `parsed_body` - A parsed-JSON representation of the response.
362 - `decoded_body` - A `Hashie::Mash` of the response body.
363
364 To set up the integration, in your `spec/spec_helper.rb` add:
365
45ed4af @fredwu Fixed some small typos and enhanced syntax highlighting in the README
fredwu authored
366 ```ruby
367 config.include RocketPants::TestHelper, :type => :controller
368 config.include RocketPants::RSpecMatchers, :type => :controller
369 ```
19b8bc5 @Sutto RSpec integration docs
authored
370
371 Inside the `RSpec.configure do |config|` block.
98d2351 @Sutto README work and License tweaks
authored
372
8ced3cb @Sutto Update README.md
authored
373 ## Contributors
374
375 - [Darcy Laycock](https://github.com/Sutto) - Main developer, current maintainer.
376 - [Steve Webb](https://github.com/swebb) - Helped with original work at [The Frontier Group](https://github.com/thefrontiergroup), inc. original design.
377 - [Fred Wu](https://github.com/fredwu) - README fixes.
378 - [Levi Buzolic](https://github.com/levibuzolic) - README fixes.
379
98d2351 @Sutto README work and License tweaks
authored
380 ## Contributing
381
382 We encourage all community contributions. Keeping this in mind, please follow these general guidelines when contributing:
383
384 * Fork the project
385 * Create a topic branch for what you’re working on (git checkout -b awesome_feature)
386 * Commit away, push that up (git push your\_remote awesome\_feature)
387 * Create a new GitHub Issue with the commit, asking for review. Alternatively, send a pull request with details of what you added.
388 * Once it’s accepted, if you want access to the core repository feel free to ask! Otherwise, you can continue to hack away in your own fork.
389
390 Other than that, our guidelines very closely match the GemCutter guidelines [here](http://wiki.github.com/qrush/gemcutter/contribution-guidelines).
391
392 (Thanks to [GemCutter](http://wiki.github.com/qrush/gemcutter/) for the contribution guide)
73b2f4e Add misc. test helpers
Darcy Laycock authored
393
98d2351 @Sutto README work and License tweaks
authored
394 ## License
73b2f4e Add misc. test helpers
Darcy Laycock authored
395
22b6142 @Sutto More readme tweaks.
authored
396 RocketPants is released under the MIT License (see the [license file](https://github.com/filtersquad/rocket_pants/blob/master/LICENSE)) and is copyright Filter Squad, 2012.
Something went wrong with that request. Please try again.