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.

520 CHAPTER 18 Rack-based applications<br />

PATH_INFO: /<br />

QUERY_STRING: ""<br />

REMOTE_ADDR: 127.0.0.1<br />

REQUEST_METHOD: GET<br />

REQUEST_URI: http://localhost:9292/<br />

...<br />

This output is the YAML-ized version of the env hash, which comes from Rack itself.<br />

Rack parses the incoming request and provides this env hash so that you can determine<br />

how you’d like to respond to the request. You can alter the behavior of the<br />

request using any one of the keys in this hash, 1 but in this case you’ll keep it simple<br />

and use the PATH_INFO key.<br />

A lambda is great for one-liners, but now your Rack application is going to become<br />

more complex, and so you’ve probably outgrown the usefulness of a lambda. You<br />

don’t have to use a lambda though, you only need to pass run an object that has a call<br />

method that responds with that three-element array. Your new code will be a couple of<br />

lines long, and so it’s probably best to define it as a method (called call) on an<br />

object, and what better object to define it on than a class?<br />

A class object would allow you to define other methods, and can be used to<br />

abstract chunks of the call method as well. For good measure, let’s call this class<br />

Application and put it inside a module called Heartbeat, as shown in the following<br />

listing:<br />

Listing 18.1 lib/heartbeat.ru<br />

module Heartbeat<br />

class Application<br />

def self.call(env)<br />

[200, {'Content-Type' => 'text/plain'}, ["Hello World"]<br />

end<br />

end<br />

end<br />

run Heartbeat::Application<br />

Here you’ve defined the Heartbeat::Application to have a call method, which once<br />

again returns OK for any request. On the final line, call run and pass in Heartbeat<br />

::Application, which will work like your first example because Heartbeat<br />

::Application has a call method defined on it. If this looks familiar, it’s because<br />

there’s a similar looking line in your application’s config.ru file that you saw earlier:<br />

run Ticketee::Application<br />

Your Rails application is actually a Rack-based application! Of course, there’s a little<br />

bit more that goes on behind the scenes in your Rails application than in your Rack<br />

application at the moment, but the two are used identically. They both respond in<br />

nearly identical ways with the three-element response array. Your Rack application is<br />

nearly the simplest form you can have.<br />

1 Yes, even the HTTP_USER_AGENT key to send users of a certain browser elsewhere.

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

Saved successfully!

Ooh no, something went wrong!