27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Mounting a Rack application with Rails<br />

params method by redefining the params method as a private method in your app.<br />

Underneath the get you’ll put this:<br />

def params<br />

hash = env["action_dispatch.request.path_parameters"].merge!(super)<br />

HashWithIndifferentAccess.new(hash)<br />

end<br />

By calling the super method here, you’ll reference the params method in the superclass,<br />

Sinatra::Base. You want to access the keys in this hash using either symbols or<br />

strings like you can do in your Rails application, so you create a new HashWith-<br />

IndifferentAccess object, which is returned by this method. This lets you access<br />

your token with either params[:token] or params["token"]. This hash is quite indifferent<br />

to its access methods.<br />

Let’s switch your root route back to calling p params. When you run your test<br />

again, you should see that you finally have both parameters inside the one hash:<br />

{:project_id=>"3", "token"=>"ZVSREe1aQjNZ2SrB9e8I"}<br />

With these parameters you’ll now be able to find the user based on their token, get a<br />

list of projects they have access to, and then attempt to find the project with the id<br />

specified. You can do this by putting two calls, a find_user and find_project<br />

method, in the before block you already have, using this code:<br />

before do<br />

headers "Content-Type" => "text/json"<br />

find_user<br />

find_project<br />

end<br />

The find_user and find_project methods can be defined underneath the private<br />

keyword using this code:<br />

private<br />

def find_user<br />

@user = User.find_by_authentication_token(params[:token])<br />

end<br />

def find_project<br />

@project = Project.for(@user).find(params[:project_id])<br />

end<br />

This code should look fairly familiar: it’s basically identical to the code found in the<br />

Api::V1::TicketsController and Api::V1::BaseController classes inside your<br />

Rack application. First you find the user based on their token and then generate a<br />

scope for all projects that the user is able to view with the Project.for method. With<br />

this scope, you can then find the project matching the id passed in through<br />

params[:project_id]. You are referencing the models from your Rails application<br />

inside your Sinatra application, and there’s nothing special you have to configure to<br />

allow this.<br />

531

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

Saved successfully!

Ooh no, something went wrong!