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.

Attaching a file<br />

You use the url B method here with link_to to provide the user with a link to<br />

download 6 this file. In this case, the URL for this file would be something like http://<br />

localhost:3000/system/assets/1/original/file.txt.<br />

Where is this system route defined? Well, it’s not a route. It’s actually a directory<br />

inside the public folder of your application where Paperclip saves your files.<br />

Requests to files from the public directory are handled by the server rather than by<br />

Rails, and anybody who enters the URL in their browser can access them. This is bad<br />

because the files in a project should be visible only to authorized users. You’ll handle<br />

that problem a little later in the chapter.<br />

Underneath the filename, you display the size of the file, which is stored in the<br />

database as the number of bytes. To convert it to a human-readable output (such as<br />

“71 Bytes,” which will be displayed for your file), you use the number_to_human_size<br />

Action View helper.<br />

With the file’s information now being output in app/views/tickets/show.html.erb,<br />

this feature passes when you run bin/cucumber features/creating_tickets<br />

.feature:<br />

4 scenarios (4 passed)<br />

52 steps (52 passed)<br />

Awesome! Your files are being uploaded and taken care of by Paperclip, which stores<br />

them at public/system/assets. Let’s see if your changes have brought destruction or salvation<br />

by running rake cucumber:ok spec:<br />

46 scenarios (46 passed)<br />

466 steps (466 passed)<br />

# and<br />

26 examples, 0 failures, 11 pending<br />

What I will say when I get through this book! Let’s commit but not push this just yet:<br />

git add .<br />

git commit -m "Added the ability to attach a file to a ticket"<br />

Have a look at the commit output. It contains this line:<br />

create mode 100644 public/system/assets/1/original/speed.txt<br />

This line is a leftover file from your test and shouldn’t be committed to the repository<br />

because you could be testing using files much larger than this. You can tell Git to<br />

ignore the entire public/system directory by adding it to the .gitignore file. Open that<br />

file now and add this line to the bottom:<br />

public/system<br />

6 Some browsers open certain files as pages rather than downloading them. Modern browsers do so for .txt files<br />

and the like.<br />

219

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

Saved successfully!

Ooh no, something went wrong!