poseid
poseid

Reputation: 7156

How does the Rails router Journey work?

Looking at the Readme of the Journey Router (which is the Rails 4.0 router), it is rather empty. I was wondering how the router works conceptually, and if this 'abstract' grammer is catching the idea, of the router as mini-programming-language:

ROUTE := GET|POST|PUT|DELETE   path
path := (static_path) | (dynamic_path) 

So, how does the Rails 4.0 Router work?

Upvotes: 8

Views: 2107

Answers (1)

Gary S. Weaver
Gary S. Weaver

Reputation: 8096

If you want to understand Rails routing, the best place to start is Rails Routing from the Outside In in the edge guide.

After that, you'll have more luck looking at ActionDispatch::Routing's docs.

Note: The following relates to Journey v1.0.4, which was the latest at time of writing.

Journey itself is the Rails routing engine introduced in Rails 3.2. In the release notes, it is described with a single statement: "Route recognition also got a bunch faster thanks to the new Journey engine." That's not a lot of info specifically about Journey, of course, but Rails doesn't describe every implementation detail; that would take forever! :) Journey's gemspec also describes itself with the statement: "Journey is a router. It routes requests."

You could look at the api docs, but in v1.0.4, it has extremely sparse documentation (Journey::Router::Utils.normalize_path(path) is documented) other than the code itself and maybe its open and closed issues. You could take a look at the other S.O. posts with tag journey.

Some of the code is somewhat self-descriptive just via method names, etc. like in Journey::Routes. Journey's tests are also a great way to see how it works.

Some notes on the code itself:

  • It monkey-patches Hash in pre-1.9 versions of Ruby to add a keep_if method.
  • "gtg" stands for "generalized transition graph" (see here)
  • Funniest code is here (Easter egg: rails c then Journey::Path::Pattern.new(9))

Journey's visualizer might be interesting to play around with, also (note visualizer method in Journey::GTG::TransitionTable). Sample visualization here, and online demo here for now.

Upvotes: 13

Related Questions