27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mounting a Rack application with Rails<br />

(which is what normally happens in a standard Rails request), a Rack class is much<br />

lighter and is perfect for serving high-intensity requests that don’t require views, like<br />

the response from your Heartbeat::Application and the responses from your API.<br />

So now that you’ve learned how you can mount your Heartbeat::Application,<br />

let’s build this slightly more complex Rack application that will serve JSON API<br />

requests for tickets. To make sure everything works, you’ll be writing tests using the<br />

same Rack::Test::Methods helpers that you used back in chapter 13. These helpers<br />

are designed for Rack applications, but they worked with your Rails application<br />

because... well, it’s a Rack app too.<br />

Rather than writing this application as a standard Rack app, let’s branch out and<br />

use another Ruby web framework called Sinatra.<br />

18.3.2 Introducing Sinatra<br />

Sinatra is an exceptionally lightweight Ruby web framework that’s perfect for building<br />

small applications, such as those that serve an API. Like Rails, it’s built on top of Rack<br />

and so you’ll have no worries about using them together. You’ll use it here to create<br />

version 3 of your API. Building you app this way not only demonstrates the power of<br />

Sinatra, but also shows that there’s more than one way to skin this particular cat. 4<br />

To install the sinatra gem, run this command:<br />

gem install sinatra<br />

You can make a small Sinatra script now by creating a file called sin.rb, as shown in the<br />

following listing.<br />

Listing 18.6 sin.rb<br />

require 'sinatra'<br />

get '/' do<br />

"Hello World"<br />

end<br />

This is the smallest Sinatra application that you can write. On the first line you require<br />

the Sinatra file, which gives you some methods you can use to define your application,<br />

such as the get method you use on the next line. This get method is used to define a<br />

root route for your application, which returns the string “Hello World” for GET<br />

requests to /. You could also make it into a class, which is what you’ll need to do for it<br />

to be mountable in your application:<br />

require 'sinatra'<br />

class Tickets < Sinatra::Base<br />

get '/' do<br />

"Hello World"<br />

end<br />

end<br />

4 Although why anybody would skin a cat these days is unknown to the authors.<br />

527

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!