Home > Articles > Programming > Ruby

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

This chapter is from the book

Route Globbing

In some situations, you might want to grab one or more components of a route without having to match them one by one to specific positional parameters. For example, your URLs might reflect a directory structure. If someone connects to

/files/list/base/books/fiction/dickens

you want the files/list action to have access to all four remaining fields. But sometimes there might be only three fields:

/files/list/base/books/fiction

or five:

/files/list/base/books/fiction/dickens/little_dorrit

So you need a route that will match (in this particular case) everything after the second URI component.

You can do that with a route glob. You "glob" the route with an asterisk:

map.connect 'files/list/*specs'

Now, the files/list action will have access to an array of URI fields, accessible via params[:specs]:

def list
  specs = params[:specs] # e.g, ["base", "books", "fiction", "dickens"]
end

The glob has to come at the end of the pattern string in the route. You cannot do this:

map.connect 'files/list/*specs/dickens'  # Won't work!

The glob sponges up all the remaining URI components, and its semantics therefore require that it be the last thing in the pattern string.

  • + Share This
  • 🔖 Save To Your Account