Home > Articles > Programming > Ruby

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

This chapter is from the book

Using Regular Expressions in Routes

Sometimes you want not only to recognize a route, but to recognize it at a finer-grained level than just what components or fields it has. You can do this through the use of regular expressions.1

For example, you could route all "show" requests so that they went to an error action if their id fields were non-numerical. You'd do this by creating two routes, one that handled numerical ids, and a fall-through route that handled the rest:

map.connect ':controller/show/:id',
  :id => /\d+/, :action => "show"

map.connect ':controller/show/:id',
  :action => "alt_show"

If you want to do so, mainly for clarity, you can wrap your regular expression-based constraints in a special hash parameter named :requirements, like this:

map.connect ':controller/show/:id',
  :action => "show", :requirements => { :id => /\d+/ }

Regular expressions in routes can be useful, especially when you have routes that differ from each other only with respect to the patterns of their components. But they're not a full-blown substitute for data-integrity checking. A URL that matches a route with regular expressions is like a job candidate who's passed a first interview. You still want to make sure that the values you're dealing with are usable and appropriate for your application's domain.

  • + Share This
  • 🔖 Save To Your Account