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.

540 CHAPTER 18 Rack-based applications<br />

will be passed as arguments to the initialize<br />

method for this middleware, and<br />

so this hash you’ve passed here will be the<br />

letters argument in your middleware.<br />

This means your LinkJumbler middleware<br />

will replace the letter e with a anytime it<br />

finds it in an a tag.<br />

To see this middleware in action, let’s<br />

fire up a server by running rails s in a ter-<br />

Figure 18.6 What’s a Tickataa?!<br />

minal. When you go to http://localhost:3000 you should notice something’s changed,<br />

as shown in figure 18.6.<br />

As you can see in this figure, your links have had their e’s replaced with a’s and any<br />

other occurrence, such as the user’s email address, has been left untouched.<br />

This is one example of how you can use middleware to affect the outcome of a<br />

request within Rails; you could have modified anything or even sent a response back<br />

from the middleware itself. The opportunities are endless. This time though, you’ve<br />

made a piece of middleware that finds all the a tags and jumbles up the letters based<br />

on what you tell it to.<br />

18.5 Summary<br />

You’ve now seen a lot of what Rack, one of the core components of the Rails stack, can<br />

offer you. In the beginning of this chapter you built a small Rack application that<br />

responded with OK. You then fleshed this application out to respond differently based<br />

on the provided request. Then you built another Rack application that called this first<br />

Rack application, running both of these within the same instance by using the<br />

Rack::Builder class.<br />

Next you saw how you could use these applications within the Rails stack by first<br />

mounting your initial Rack application and then branching out into something a little<br />

more complex, with a Sinatra-based application serving what could possibly be the<br />

beginnings of version 3 of Ticketee’s API. Sinatra is a lightweight framework offering<br />

the same basic features as Rails.<br />

Finally, you saw two pieces of middleware, the ActionDispatch::Static piece and<br />

the ActionDispatch::BestStandardsSupport. You dissected the first of these, figuring<br />

out how it worked so that you could use that knowledge to build your own middleware,<br />

a neat little piece that jumbles up the text on the link based on the options<br />

passed to it.

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

Saved successfully!

Ooh no, something went wrong!