Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Static Strings

Our sample route contains a static string inside the pattern string: recipes.

map.connect 'myrecipes/:ingredient',
            :controller => "recipes",
            :action => "show"

This string anchors the recognition process. When the routing system sees a URL that starts /recipes, it will match that to the static string in the ingredient route. Any URL that does not contain the static string recipes in the leftmost slot will not match this route.

As for URL generation, static strings in the route simply get placed, positionally, in the URL that the routing system generates. Thus the link_to example we've been considering

<%= link_to "My Apple Recipes",
      :controller => "recipes",
      :action     => "show",
      :ingredient => "apples" %>

will generate the following HTML:

<a href="http://localhost:3000/myrecipes/apples">My Apple Recipes</a>

The string myrecipes did not appear in the link_to call. The parameters of the link_to call triggered a match to the ingredients route. The URL generator then used that route's pattern string as the blueprint for the URL it generated. The pattern string stipulates the substring myrecipes.

URL recognition and URL generation, then, are the two jobs of the routing system. It's a bit like the address book stored in a cell phone. When you select "Gavin" from your contact list, the phone looks up the phone number. And when Gavin calls you, the phone figures out from the number provided by caller ID that the caller is Gavin; that is, it recognizes the number and maps it to the value "Gavin", which is displayed on the phone's screen.

Rails routing is a bit more complex than cell phone address book mapping, because there are variables involved. It's not just a one-to-one mapping. But the basic idea is the same: recognize what comes in as requests, and generate what goes into the code as HTML.

We're going to turn next to the routing rules themselves. As we go, you should keep the dual purpose of recognition/generation in mind. There are two principles that are particularly useful to remember:

  • The same rule governs both recognition and generation. The whole system is set up so that you don't have to write rules twice. You write each rule once, and the logic flows through it in both directions.
  • The URLs that are generated by the routing system (via link_to and friends) only make sense to the routing system. The path recipes/apples, which the system generates, contains not a shred of a clue as to what's supposed to happen—except insofar as it maps to a routing rule. The routing rule then provides the necessary information to trigger a controller action. Someone looking at the URL without knowing the rules won't know what the URL means.

You'll see how these play out in detail as we proceed.

  • + Share This
  • 🔖 Save To Your Account