In this lab we will use AJAX to request data from an API about wine. We will use jQuery make an AJAX request to http://daretodiscover.net/wine and display the resulting list of wines. This should all be done in the context of a Ruby on Rails app.
- Create a Ruby on Rails app.
- Make a controller and route that renders a home page.
- On the home page, include JavaScript that calls
http://daretodiscover.net/wine.
- Hint: by default Rails gives us a
.coffee
file. Replace it with a.js
file and remove the coffeescript-style comments. - Hint: use one of jQuery's
$.ajax
or$.getJSON()
methods.
- Hint: by default Rails gives us a
- When the results are returned, make sure you can log them to the
console
.- Ponder: what datatype is the result?
- Ponder: how will you be able to turn the returned data into an HTML list?
- Start to render the list of wines onto the page via JavaScript and
realize there must be a better way.
- Hint: would you use
document.createElement("ul")
? - Hint: could you use
$("<ul>")
?
- Hint: would you use
- Decide to integrate Handlebars templates instead of using either of those options.
-
Include the
handlebars_assets
gem in your Gemfile.# Gemfile gem 'handlebars_assets'
-
Don't forget to run
bundle install
and then restart your Rails server.bundle install rails server
-
Create a folder called
templates
in yourapp/assets/javascripts
folder.# inside of app/assets/javascripts directory mkdir templates
-
Add a
.hbs
template in your newly createdtemplates
directory.# inside of templates directory touch wine.hbs
-
Add the following lines to
application.js
so it includes the Handlebars template you've created.//= require handlebars.runtime //= require_tree ./templates
Careful: Does the handlebars_assets documentation say anything specific about where
require_tree ./templates
needs to be included relative torequire_tree .
? -
Add some Handlebars syntax to your
.hbs
file. You may want to check out{{#each}}
. -
In your original JavaScript file, access your new template though
var template = HandlebarsTemplates["wine"]; var html = template(wineResultsJSON); // render that html to the page (w/ jQuery?)
-
Fix bugs (and read docs) until it works.