jQuery and Rails: Best Friends Forever


Published on

Covers techniques on building a rich web application with jQuery and Rails. Topics include jQuery, Ruby on Rails, AJAX, JSON, and the data tag.

Published in: Technology
1 Comment
  • Raspberry Ketone Thin soon spread to local schools. Flunkies didn't sound much more optimistic touching on Raspberry Ketone Thin. Yes, that rarely happens to everyone. I was correct.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Also known for it's chaining model
  • - 360k sites use jQuery, as compared to 55k MooTools, 39k Prototype, 30k YUI, 9k script.aculo.us - 66% of web page visits use jQuery
  • - what are the bare minimum, step by step - context, onstart, tons of arguments
  • - routing is akin to Interchange actionmaps (although evolved, more complex) - rendering :json automaticallly calls a to_json method on the data
  • - the request object contains a lot of useful information about the request: host, domain, format, method, type of request, headers, port, protocol, etc.
  • ParseJSON is a jQuery specific function, while JSON.stringify is not a part of the jQuery library (JSON also has it's own parse method). to_json nested elements might include images belonging to product
  • - only works in HTML5 - in addition to id, you may also want to track nested ids, or other information about that comment that has little to do with CSS styles - jQuery has getter and setter methods here, for data - e.g. of use: multiple comments on one page, but HTML for one form. When click on edit comment, data is set to identify which comment is being edited.
  • - writing your own HTML can be messy, but give you full control - using a template system encourages DRY - using a client side model-view paradigm may result in reproducing business logic for an individual model (that business logic also lives on the server side) - disadvantage to all: you aren't leveraging server side functionality or helpers for building Rails forms - advantage to all: speed, less dependency on server for AJAX hits
  • jQuery and Rails: Best Friends Forever

    1. jQuery & Rails Best Friends Forever* Best Friends Forever* *Forever as used by a 6th-grader *Forever in the sense of a sixth grader.
    2. Ill Cover:● Brief Rails explanation● Brief jQuery explanation● Nice methods between each technology to encourage a rich web app ● AJAX ● JSON ● data● The Future
    3. jQuery...● is a JavaScript framework (YUI, prototype, scriptaculous)● includes basic JavaScript functionality for AJAX, DOM manipulation, events● likes to hang out with jQuery UI, user interface library, interactions, widgets, effects, themes● is known for being concise and readable http://jqueryui.com/
    4. Popularityhttp://www.webappers.com/infographics/javascript-frameworks-jquery.html
    5. Ruby on Rails...● is a MVC framework built on Ruby● is a tool for efficient development that follows universal conventions● is designed to work well with JavaScript + AJAX
    6. AJAX in jQuery$.ajax({ url: "test.html", data: $(#form).serialize(), type: “POST”, cache: false, dataType: “html”, success: function(){ //do something }, error: function() { //do something else }}); http://api.jquery.com/jQuery.ajax/
    7. Rails Tidbits● Routing: connects URLs to Code match “/products/:id” => “products#show”● Handling different responses respond_to do |format| format.html format.xml { … } end● Handling JSON response respond_to do |format| format.json { render :json => data } end
    8. Rails Tidbits● Request object request.xhr?● Handling CGI parameters params[:name], params[:description] params.has_key?(:name) p = Product.new(params[:product]) p.save # check for p.errors product.update_attributes(params[:product])
    9. Ponghttp://www.bafta.org/awards/video-games/play-pong-online,678,BA.html
    10. User: Initiates Action //jQuery wrapper method $.fn.comment_photo = function() { //do stuff } $(function() { $(.comment-photo).click(function() { $(this).comment_photo(); }); })
    11. jQuery: AJAX call $.fn.comment_photo = function() { $.ajax({ url: “/comment/new", data: { photo_id: this.attr(id) }, cache: false, dataType: “html” … }); }
    12. Rails: calls Controllerclass CommentsController < ApplicationController def new @comment = Comment.new respond_to do |format| format.html #new.html.erb end endend
    13. Rails: renders HTML erb HTML<% form_for @comment do |f| %> <form action= “/comments” method=”post”> <%= f.label :title %> <label for=“comment_title”>Title</label> <%= f.text_field :title %> <input type=“text” id=“comment_title” name=“comment[title]” /> <%= f.label :data %> <label for=“comment_data”>Data</label> <%= f.text_area :data %> <textarea id=“comment_data” name=“comment[data]” /></textarea> <%= f.submit %> <input type=“submit” id=“comment_submit” value=”Create ” /><% end %> </form> http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/
    14. jQuery: displays HTML $.fn.comment_photo = function() { $.ajax({ … success: function(html) { $(#new_comment).html(html); } }); }
    15. User: more action //extending jQuery object $.extend({ create_comment: function(form) { //do stuff } }); $(function() { $(#new_comment).submit(function() { $.create_comment($(this)); }); })
    16. jQuery: AJAX call create_comment: function(form) { $.ajax({ url: form.attr(action), type: “POST”, data: { comment: form.serialize() }, cache: false, dataType: “JSON” … }); }
    17. Rails: calls Controller class CommentsController < ApplicationController def create begin comment = Comment.new(params[:comment]) comment.user = current_user comment.save respond_to do |format| format.json :json => comment end rescue Exception => e render :status => 500, :json => {} end end end
    18. jQuery: success! create_comment: function(comment) { $.ajax({ … success: function(result) { $(#new_comment).hide(); //feedback to communicate success }, error: function(xhr, status, error) { //feedback to communicate error } }); }
    19. Interchange User jQuery ActionMap Perl Module ActionMap will route URL to desired functionality. HTML jQuery Perl Module will set mv_nextpage and set Scratch variables. jQuery JSON Perl Module can use JSON module to set Scratch variable to JSON-ified data.Perl Module ActionMap jQuery User
    20. Pagination respond_to do |format| format.html do if request.xhr? success:function() { render :partial => item_block //replace HTMLdataType: “html” else //apply listeners render index //replace pagination end } end end
    21. .js & js.erbIts worth noting that you can also return JavaScript or JavaScript froma js.erb file as a Rails controller response. erb is a templating language.The resulting JavaScript will be executed by jQuery. respond_to do |format| format.js { render :text => "alert(hello)" } endI prefer returning JSON, because Ive seen this be finicky and it can bedifficult to debug.
    22. JSON jQuery and JavaScript Railsvar obj = $.parseJSON(string); render :json => comment//parse a string into a JSON object # automatically calls to_jsonJSON.stringify(obj); to_json//stringify a JSON object into JSON # converts objects to string//text for use as argument string # arguments: only, except, include # nested resources http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
    23. data tag & HTML5 Rails <div id=“comment” data-id=“<%= comment.id %>”> </div> jQuery $(.comment).data(id); $(.comment).data(id, 123); $(.comment).removeData(id); everything in moderation.
    24. The FutureUser jQuery Controller HTML jQuery What if you want to skip the first AJAX call for performance? User jQuery JSON Controller jQuery
    25. The Future Options for eliminating first AJAX call● Render HTML form inline (once)● Render HTML form in JavaScript with jQuery HTML builder nodes● Use a template system like Mustache.js or Handlebars.js● Use a JavaScript [client-side] Model-View framework like Backbone.js
    26. Mustache.js Edit { }var comment_template = “<h3>{{header}}</h3> var comment = { header: “Edit your Comment!”, title: “Awesome”, data: “This is an awesome photo.”<p class=“error”></p> };<label for=“title”>Title</label> $.mustache(comment_template, comment);<input type=“text” name=“title” value=“{{title}}” /><label for=“data”>Data</label><textarea name=“data”>{{data}}</textarea> New<input type=“submit” value= “submit” />”; var comment = { header: “Comment on This!” }; $.mustache(comment_template, comment); http://mustache.github.com/
    27. Disclaimer● Other modern javascript frameworks have much of the same functionality here, specifically YUI. You have a choice. http://developer.yahoo.com/yui/
    28. jQuery & Rails● jQuery and Rails work together to write rich web applications.● jQuery is most popular and known for its conciseness and readability, and unique “chaining” method● DIG into the documentation. jQuery and Ruby documentation is good. Rails is “up and coming”. http://visualjquery.com/
    29. Photo Credits● http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best● me: http://www.flickr.com/photos/just_steph/
    30. Questions?