jQuery and Rails: Best Friends Forever
Upcoming SlideShare
Loading in...5
×
 

jQuery and Rails: Best Friends Forever

on

  • 28,099 views

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

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

Statistics

Views

Total Views
28,099
Views on SlideShare
22,914
Embed Views
5,185

Actions

Likes
6
Downloads
101
Comments
1

15 Embeds 5,185

http://www.endpoint.com 4475
http://blog.endpoint.com 366
http://mobile.osnews.com 197
http://localhost 78
http://www.osnews.com 17
http://64.camp.endpoint.com 11
http://translate.googleusercontent.com 9
http://paper.li 9
http://my-academy.tumblr.com 8
http://webcache.googleusercontent.com 7
https://twitter.com 4
http://kred.com 1
http://www.hanrss.com 1
http://us-w1.rockmelt.com 1
http://74.6.116.71 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • 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.
    http://raspberryketonethinsite.com
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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 jQuery and Rails: Best Friends Forever Presentation Transcript

  • jQuery & Rails Best Friends Forever* Best Friends Forever* *Forever as used by a 6th-grader *Forever in the sense of a sixth grader.
  • Ill Cover:● Brief Rails explanation● Brief jQuery explanation● Nice methods between each technology to encourage a rich web app ● AJAX ● JSON ● data● The Future
  • 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/
  • Popularityhttp://www.webappers.com/infographics/javascript-frameworks-jquery.html
  • 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
  • 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/
  • 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
  • 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])
  • Ponghttp://www.bafta.org/awards/video-games/play-pong-online,678,BA.html
  • User: Initiates Action //jQuery wrapper method $.fn.comment_photo = function() { //do stuff } $(function() { $(.comment-photo).click(function() { $(this).comment_photo(); }); })
  • jQuery: AJAX call $.fn.comment_photo = function() { $.ajax({ url: “/comment/new", data: { photo_id: this.attr(id) }, cache: false, dataType: “html” … }); }
  • Rails: calls Controllerclass CommentsController < ApplicationController def new @comment = Comment.new respond_to do |format| format.html #new.html.erb end endend
  • 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/
  • jQuery: displays HTML $.fn.comment_photo = function() { $.ajax({ … success: function(html) { $(#new_comment).html(html); } }); }
  • User: more action //extending jQuery object $.extend({ create_comment: function(form) { //do stuff } }); $(function() { $(#new_comment).submit(function() { $.create_comment($(this)); }); })
  • jQuery: AJAX call create_comment: function(form) { $.ajax({ url: form.attr(action), type: “POST”, data: { comment: form.serialize() }, cache: false, dataType: “JSON” … }); }
  • 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
  • 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 } }); }
  • 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
  • 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
  • .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.
  • 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
  • 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.
  • The FutureUser jQuery Controller HTML jQuery What if you want to skip the first AJAX call for performance? User jQuery JSON Controller jQuery
  • 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
  • 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/
  • Disclaimer● Other modern javascript frameworks have much of the same functionality here, specifically YUI. You have a choice. http://developer.yahoo.com/yui/
  • 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/
  • Photo Credits● http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best● me: http://www.flickr.com/photos/just_steph/
  • Questions?