title: How do I modify the request object before routing in Rails in a testable way?
body: <p>So, I have a situation where I need to determine something about a request before it is dispatched to any of the routes. Currently, this is implemented using several constraints that all hit the database, and I want to reduce the database hit to one.  Unfortunately, doing it inline in <code>routes.rb</code> doesn't work, because the local variables within <code>routes.rb</code> don't get refreshed between requests; so if I do:</p>
  
  <pre><code># Database work occurs here, and is then used to create comparator lambdas.
  request_determinator = RequestDeterminator.new(request)
  
  constraint(request_determinator.lambda_for(:ninja_requests)) do
    # ...
  end
  
  constraint(request_determinator.lambda_for(:pirate_requests)) do
    # ...
  end
  </code></pre>
  
  <p>This works great on the first request, but then subsequent requests get routed as whatever the first request was.  (D'oh.)</p>
  
  <p>My next thought was to write a Rack middleware to add the "determinator" to the <code>env</code> hash, but there are two problems with this: first, it doesn't seem to be sticking in the hash at all, and specs don't even go through the Rack middleware, so there's no way to really test it.</p>
  
  <p>Is there a simple mechanism I'm overlooking where I can insert, say, a hook for ActionDispatch to add something to the request, or just to say to Rails routing: "Do this before routing?"</p>
  
  <p>I am using Rails 3.2 and Ruby 1.9. </p>