27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

530 CHAPTER 18 Rack-based applications<br />

By placing this mount call inside the namespaces, the Rack application will be<br />

mounted at /api/v3/json/projects/:project_id/tickets rather than the /tickets URI if<br />

you didn’t have it nested. Additionally, you’ve specified a dynamic parameter in the<br />

form of :project_id. With this, you’ll be able to access the requested project id from<br />

inside your Rack application using a method very similar to how you’d usually access<br />

parameters in a controller.<br />

If you attempted to run your spec again it would bomb out with another new error:<br />

expected "[tickets array]"<br />

got ""<br />

This means that requests are able to get to your Rack app and that the response you’ve<br />

declared is being served successfully. Now you need to fill this response with meaningful<br />

data. To do this, find the project that’s being referenced in the URL by using the<br />

parameters passed through found with the params method. Unfortunately, Sinatra<br />

doesn’t load the parameters from your Rails application and so params[:project_id]<br />

is not going to be set. You can see this if you change your root route in your Sinatra<br />

application to this:<br />

get '/' do<br />

p params<br />

end<br />

Then if you run your test, you’ll see only the token parameter is available:<br />

{"token"=>"6E06zoj01Pf5texLXVNb"}<br />

Luckily, you can still get to this through one of the keys in the environment hash,<br />

which is accessible through the env method in your Sinatra actions, like it was available<br />

when you built your Rack applications. You saw this environment hash earlier<br />

when you were developing your first Rack application, but this time it’s going to have<br />

a little more to it because it’s gone through the Rails request stack. Let’s change your<br />

root route to this:<br />

get '/' do<br />

p env.keys<br />

end<br />

When you rerun your test, you’ll see all the available keys output at the top, with one of<br />

the keys being action_dispatch.request.path_parameters. This key stores the<br />

parameters discovered by Rails routing, and your project_id parameter should fall<br />

neatly into this category. Let’s find out by changing the p env.keys line in your root<br />

route to p env["action_dispatch.request.path_parameters"] and then re-running<br />

your test. You should see this:<br />

{:project_id=>"3"}<br />

Okay, so you can access two parameter hashes, but you’ll need to merge them<br />

together if you are to do anything useful with them. You can merge them into a super

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!