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.

230 CHAPTER 9 File uploading<br />

When you rerun your specs, they both pass because the authorized user (good_user)<br />

can get a file and the unauthorized user (bad_user) can’t:<br />

2 examples, 0 failures<br />

Great! Now you’ve begun to serve the files from FilesController to only people who<br />

have access to the asset’s relative projects. There’s one problem, though: all users can<br />

still access these files without having to go through the FilesController.<br />

9.3.3 Public assets<br />

People can still get to your files as long as they have the<br />

link provided to them because the files are still stored<br />

in the public folder. Let’s see how this is possible by<br />

starting up the server using rails server, signing in,<br />

and creating a ticket. Upload the spec/fixtures/spin.txt<br />

file as the only file attached to this ticket. You should<br />

see a ticket like the one in figure 9.2.<br />

Hover over the spin.txt link on this page, and<br />

you’ll see a link like this:<br />

http://localhost:3000/system/assets/5/original/spin.txt?1282564953<br />

As you saw earlier in this chapter, this link is a route not to a controller in your application<br />

but to a file inside the public directory. Any file in the public directory is accessible<br />

to the public. Sensible naming schemes rock!<br />

If you copy the link to this file, sign out, and then paste the link into your browser<br />

window, you can still access it. These files need to be protected, and you can do that by<br />

moving them out of the public directory and into another directory at the root of your<br />

application called files. You should create this directory now.<br />

9.3.4 Privatizing assets<br />

Figure 9.2 A ticket with spin!<br />

You can make these files private by storing them in the files folder. You don’t have to<br />

move them there manually: you can tell Paperclip to put them there by default by<br />

passing the :path option to has_attached_file in app/models/asset.rb like this:<br />

has_attached_file :asset, :path => (Rails.root + "files/:id").to_s<br />

Now try creating another ticket and attaching the spec/fixtures/spin.txt file. This time<br />

when you use the link to access the file, you’re told there’s no route. This is shown in<br />

figure 9.3.<br />

Figure 9.3 No route!

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

Saved successfully!

Ooh no, something went wrong!