Some Common Tricks with Ruby on Rails
- Autocomplete in a text box
- Uploading files by dragging and dropping them into an area inside a browser.
- Download the JS file for the library. It is a “jQuery plugin” which means that it acts as an extension to the jQuery $ function.
- Set the HTML id attribute for the textbox you want to “adorn” with autocomplete functionality.
- Use the jQuery extension .tokeninput, to add the functionality.
The values specified have to be returned in a specific format – as a Hash, with an id and a name key. The script will use either one of those depending on how you configure it, to send to the server when you submit the form.
To hook this up to your Rails backend, you need a route that acts as an “API” which can be used in an AJAX call by the token-input script. The route has to point to a controller which will return the Hash in a JSON format.
In Rails 4, you can easily create JSON formatted responses by using the
render json: data construct inside your controller.
And voila! You have a simple autocomplete functionality you can use in any form.
Drag-and-Drop File Upload
To get this functionality, the first thing to think about is how the browser knows that you are dragging something into it. Information like this is usually fed to the browser via “events.” In this case, the events we care most about are the drag and dragenter events – read about more of them on the Mozilla Developer Networks page.
Additionally, when we handle the events, we need to know how to manage the file’s contents – we do this via the File API which is a feature introduced in HTML5. Most major browsers today support this interface – unfortunately, the holdouts which are IE versions 6 through 9, still have about 10% market share, so a significant portion of the population will not be able to use this feature if you code it without the right workarounds.
Eric Bidelman on HTML5 Rocks has a great tutorial, that’s worth understanding. It goes into the details of how files are read in the browser.
On the MDN website, there is example code that completes this process with an example on how to construct an XHR request, to post the file as part of the form data in a POST request.
On the back-end, now you have to figure out how to read the “multipart form data” that has been sent in the HTTP request. In Rails, you can access the file data very easily by treating the incoming parameter in the params array as a File IO object (like the one you would create in Ruby if you used File.open.)
A simple read call on the IO object will then give you the full contents of the file on the server side.