SlideShare a Scribd company logo
1 of 58
Download to read offline
UJS in
      Rails 3
Tuesday, February 1, 2011
UJS in
      Rails 3               by Phil Crissman
Tuesday, February 1, 2011
Rails and Javascript




Tuesday, February 1, 2011
Rails and Javascript

       Javascript helpers have been built into
       Rails from the very earliest versions.

       Prototype and Ajaxy helpers have
       traditionally been “just there” and have
       always “just worked”



Tuesday, February 1, 2011
Rails and Javascript

       Javascript helpers have been built into
       Rails from the very earliest versions.

       Prototype and Ajaxy helpers have
                                        Magic
       traditionally been “just there” and have
       always “just worked”



Tuesday, February 1, 2011
Tuesday, February 1, 2011
Tuesday, February 1, 2011
Unobtrusive Javascript




Tuesday, February 1, 2011
Unobtrusive Javascript

         Unobtrusive Javascript is simply the idea
         of keeping your behavior-defining script
         out of your content.

         It’s the same idea as keeping your style-
         defining rules (CSS) out of your content.



Tuesday, February 1, 2011
Unobtrusive Javascript
       So instead of:
       <a href="#" onclick="alert('ok!');"> Hey </a>

       We would do:
       <a href="#" class="alerty"> Hey </a>
       ...
       <script type="javascript">
       $(function(){
           $('.alerty').click(function(){
             alert('ok!');
           });
       });
       </script>
Tuesday, February 1, 2011
Unobtrusive Javascript
       Is ‘unobtrusive’ Javascript ‘better’?




Tuesday, February 1, 2011
Unobtrusive Javascript
       Is ‘unobtrusive’ Javascript ‘better’?




Tuesday, February 1, 2011
Unobtrusive Javascript
       Is ‘unobtrusive’ Javascript ‘better’?

                            WELL, THAT’S JUST, LIKE


                                YOUR OPINION


                                     MAN




Tuesday, February 1, 2011
Unobtrusive Javascript


       Making Javascript ‘unobtrusive’ won’t
       magically make your code any better.

       But...




Tuesday, February 1, 2011
Unobtrusive Javascript



       It’s ‘better’ in the same sense that separating
       style from content is ‘better’.




Tuesday, February 1, 2011
Unobtrusive Javascript



       And it’s how Javascript helpers are handled by
       default in Rails 3.




Tuesday, February 1, 2011
Unobtrusive Javascript


       In the past, if you wanted to use unobtrusive
       javascript techniques in Rails, you simply
       stopped using the built-in Javascript helpers...

       And wrote all your Javascript from scratch.




Tuesday, February 1, 2011
Unobtrusive Javascript


       In Rails 3, you get to keep using the built-in
       Javascript helpers...

       And still write all your Javascript from scratch.




Tuesday, February 1, 2011
Unobtrusive Javascript


       In Rails 3, you get to keep using the built-in
       Javascript helpers...

       And still write all your Javascript from scratch.




Tuesday, February 1, 2011
UJS in Rails 3




Tuesday, February 1, 2011
UJS in Rails 3
       Rails 3 makes several changes to the
       Javascript helpers:




Tuesday, February 1, 2011
UJS in Rails 3
       Rails 3 makes several changes to the
       Javascript helpers:
       1. Instead of inserting inline JS, Rails 3 uses
       HTML5 data- attributes.




Tuesday, February 1, 2011
UJS in Rails 3
       Rails 3 makes several changes to the
       Javascript helpers:
       1. Instead of inserting inline JS, Rails 3 uses
       HTML5 data- attributes.
       2. No more ‘remote’ helpers (link_to_remote,
       remote_form_for, et al., are gone).




Tuesday, February 1, 2011
UJS in Rails 3
       Rails 3 makes several changes to the
       Javascript helpers:
       1. Instead of inserting inline JS, Rails 3 uses
       HTML5 data- attributes.
       2. No more ‘remote’ helpers (link_to_remote,
       remote_form_for, et al., are gone).
       3. It’s a lot easier to pull out Prototype and
       switch to jQuery or mootools, etc, if you want
       to.

Tuesday, February 1, 2011
UJS in Rails 3

       1. Data attributes.

       Rails takes advantage of a new feature of
       HTML5: any tag can have any number of
       attributes prepended with “data-”, and still be
       perfectly valid markup.




Tuesday, February 1, 2011
UJS in Rails 3


       Common use case: deleting something, via a
       link:
       <%= link_to "Delete", posts_path(@post),
       :method => "delete", :confirm => "Are you
       sure?" %>




Tuesday, February 1, 2011
UJS in Rails 3
       Would render (pre Rails 3) as:
       <a href="/posts/1" onclick="if (confirm('Are you sure?')) { var
       f = document.createElement('form'); f.style.display = 'none';
       this.parentNode.appendChild(f); f.method = 'POST'; f.action =
       this.href;var m = document.createElement('input');
       m.setAttribute('type', 'hidden'); m.setAttribute('name',
       '_method'); m.setAttribute('value', 'delete'); f.appendChild
       (m);var s = document.createElement('input'); s.setAttribute
       ('type', 'hidden'); s.setAttribute('name',
       'authenticity_token'); s.setAttribute('value',
       'nMxiiHBFyQr9Q3Jc7QGzSd1tk08ujbsHhtF3S26k/k8='); f.appendChild
       (s);f.submit(); };return false;">Delete</a>




Tuesday, February 1, 2011
UJS in Rails 3
       Would render as:
       <a href="/posts/1" onclick="if (confirm('Are you sure?')) { var
       f = document.createElement('form'); f.style.display = 'none';
       this.parentNode.appendChild(f); f.method = 'POST'; f.action =
       this.href;var m = document.createElement('input');
       m.setAttribute('type', 'hidden'); m.setAttribute('name',
       '_method'); m.setAttribute('value', 'delete'); f.appendChild

                                                      Magic
       (m);var s = document.createElement('input'); s.setAttribute
       ('type', 'hidden'); s.setAttribute('name',
       'authenticity_token'); s.setAttribute('value',
       'nMxiiHBFyQr9Q3Jc7QGzSd1tk08ujbsHhtF3S26k/k8='); f.appendChild
       (s);f.submit(); };return false;">Delete</a>




Tuesday, February 1, 2011
UJS in Rails 3
       In Rails 3, this same link_to statement...

       <%= link_to "Delete", posts_path
       (@post), :method => "delete", :confirm => "Are
       you sure?" %>

       ...will render as:

       <a href="/posts/1" data-confirm="Are you
       sure?" data-method="delete"
       rel="nofollow">Delete</a>



Tuesday, February 1, 2011
UJS in Rails 3
       In Rails 3, this same link_to statement...

       <%= link_to "Delete", posts_path
       (@post), :method => "delete", :confirm => "Are
       you sure?" %>

       ...will render as:

       <a href="/posts/1" data-confirm="Are you
       sure?" data-method="delete"
       rel="nofollow">Delete</a>



Tuesday, February 1, 2011
UJS in Rails 3
         ‘data-method’ and ‘data-confirm’ attributes
         (and everything else) are handled from
         /public/javascripts/rails.js

       // from the jQuery version of rails.js:

       function allowAction(element) {
       	 	 var message = element.attr('data-confirm');
       	 	 return !message || (fire(element, 'confirm') && confirm
       (message));
       	 }




Tuesday, February 1, 2011
UJS in Rails 3


       2. ‘remote’ helpers.

       Instead of helpers like link_to_remote, in Rails
       3, :remote is a param that you include with
       your link or your form.




Tuesday, February 1, 2011
UJS in Rails 3


       So if we want to make our delete link ajaxy:

       <%= link_to "Delete", posts_path
       (@post), :method => "delete", :confirm => "Are
       you sure?", :remote => true %>




Tuesday, February 1, 2011
UJS in Rails 3


       So if we want to make our delete link ajaxy:

       <%= link_to "Delete", posts_path
       (@post), :method => "delete", :confirm => "Are
       you sure?", :remote => true %>




Tuesday, February 1, 2011
UJS in Rails 3
       This will render (you guessed it) as:

       <a href="/posts/1" data-confirm="Are you
       sure?" data-method="delete" data-remote="true"
       rel="nofollow">Delete</a>




Tuesday, February 1, 2011
UJS in Rails 3
       This will render (you guessed it) as:

       <a href="/posts/1" data-confirm="Are you
       sure?" data-method="delete" data-remote="true"
       rel="nofollow">Delete</a>

       And clicking on it will fire a function in rails.js
       which creates an XMLHttpRequest and sends
       it to the URL in your href attribute.



Tuesday, February 1, 2011
UJS in Rails 3


       3. Replacing Prototype with jQuery, mootools,
       or...

       Rails 3 has made this very simple.




Tuesday, February 1, 2011
UJS in Rails 3

       If we want to use jQuery, for example, we
       simply add to our Gemfile:

       gem 'jquery-rails'

       And then (in the terminal) :
       % bundle install
       % rails g jquery:install




Tuesday, February 1, 2011
UJS in Rails 3
       Side note: RJS

       If you use RJS, just adding jquery-rails does
       not (at the moment, at least) provide jQuery
       equivalents for RJS statements.

       You may be able to use jrails, which does (or at
       least did) provide these. (I haven’t tried this.)

       Otherwise, you’ll want to stick with Prototype.


Tuesday, February 1, 2011
UJS in Rails 3: an example




Tuesday, February 1, 2011
UJS in Rails 3: an example



       Let’s actually make it work. Even if not using
       RJS, there are still a couple ways we can
       respond to the xhr sent by our delete link.




Tuesday, February 1, 2011
UJS in Rails 3: an example



       1. You could write a javascript template; for a
       destroy action, this might be destroy.js.erb (or
       destroy.js.haml)...




Tuesday, February 1, 2011
UJS in Rails 3: an example


       This might look something like:

       / destroy.js.haml
       $("#posts").html("#{escape_javascript(render
       (@posts))}");




Tuesday, February 1, 2011
UJS in Rails 3: an example



       2. Or, you might write javascript hooks straight
       into application.js, which will be called at the
       appropriate time.




Tuesday, February 1, 2011
UJS in Rails 3: an example

       In public/javascripts/application.js:

       $(function(){
         $('#posts a').bind("ajax:complete", function
       (n, xhr){
           $(this).parent().parent().fadeOut(4000);
         });
       });




Tuesday, February 1, 2011
UJS in Rails 3: an example
       There are several events fired with each xhr
       (they differ slightly between the Prototype and
       jQuery version of rails.js):

      // Prototype rails.js     // jQuery rails.js
      ajax:before               ajax:beforeSend
      ajax:success              ajax:success
      ajax:complete             ajax:complete
      ajax:failure              ajax:error
      ajax:after




Tuesday, February 1, 2011
Obtrusive Javascript
       But, if you’re determined to cling to the past:




Tuesday, February 1, 2011
Obtrusive Javascript
       But, if you’re determined to cling to the past:




Tuesday, February 1, 2011
Recap:




Tuesday, February 1, 2011
Recap:
       Rails has a long history of tightly integrating Javascript
       view helpers; Rails 3 continues this.




Tuesday, February 1, 2011
Recap:
       Rails has a long history of tightly integrating Javascript
       view helpers; Rails 3 continues this.
       However, in Rails 3, these helpers aim to be
       unobtrusive.




Tuesday, February 1, 2011
Recap:
       Rails has a long history of tightly integrating Javascript
       view helpers; Rails 3 continues this.
       However, in Rails 3, these helpers aim to be
       unobtrusive.
       Rails 3 js changes include:
       1. Utilizing HTML5 data-* attributes.
       2. Adding a :remote param to helpers that can use it.
       3. Making it easy to drop in alternate JS frameworks in
       place of Prototypejs.




Tuesday, February 1, 2011
Recap:
       Rails has a long history of tightly integrating Javascript
       view helpers; Rails 3 continues this.
       However, in Rails 3, these helpers aim to be
       unobtrusive.
       Rails 3 js changes include:
       1. Utilizing HTML5 data-* attributes.
       2. Adding a :remote param to helpers that can use it.
       3. Making it easy to drop in alternate JS frameworks in
       place of Prototypejs.
       You can either use a js template to send js right back
       to the browser, or you can take advantage of the ajax
       hooks provided by rails.js.

Tuesday, February 1, 2011
Resources:



       There are several books recently or soon-to-be
       published covering Rails 3; most seem to have little or
       no coverage of unobtrusive JS.




Tuesday, February 1, 2011
Resources:


       Rails 3 in Action, by Yehuda Katz (@wycats) and Ryan
       Bigg (@ryanbigg), will contain some examples of UJS.
       It’s not complete yet, but if you’re interested in
       checking it out (http://manning.com/katz/), there is a
       discount code (50% off; valid Jan 23 to Feb 23):
       rails350




Tuesday, February 1, 2011
Resources:



       Otherwise, your best bet seems to be searching for
       blog posts and reading the Rails 3 source (particularly
       rails.js).




Tuesday, February 1, 2011
Questions?




Tuesday, February 1, 2011
railroad closeup: http://www.flickr.com/photos/ericrice/25207672/sizes/m/in/photostream/
                    railroad clock: http://www.flickr.com/photos/dougtone/4127322153/sizes/z/in/photostream/
                    train picture: http://www.flickr.com/photos/eterno_retorno/2383602431/sizes/z/in/photostream/




Tuesday, February 1, 2011

More Related Content

Similar to UJS in Rails 3

Adopting DLM at Greentube
Adopting DLM at GreentubeAdopting DLM at Greentube
Adopting DLM at GreentubeAlex Yates
 
jQuery Tips'n'Tricks
jQuery Tips'n'TricksjQuery Tips'n'Tricks
jQuery Tips'n'TricksNikola Plejic
 
(WS11) Nikola Plejić: jQuery tips & tricks
(WS11) Nikola Plejić: jQuery tips & tricks(WS11) Nikola Plejić: jQuery tips & tricks
(WS11) Nikola Plejić: jQuery tips & tricksWeb::Strategija
 
Rails 3.1 Asset Pipeline
Rails 3.1 Asset PipelineRails 3.1 Asset Pipeline
Rails 3.1 Asset Pipelineeallam
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPsmueller_sandsmedia
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Gautam Rege
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기형우 안
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4alexsaves
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course JavaEE Trainers
 
Ruby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksRuby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksinfovore
 
HTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsHTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsChrome Developer Relations
 
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...Alexandre Porcelli
 
Unleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineUnleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineKenneth Kalmer
 
Better front-end development in Atlassian plugins
Better front-end development in Atlassian pluginsBetter front-end development in Atlassian plugins
Better front-end development in Atlassian pluginsAtlassian
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIAashish Jain
 

Similar to UJS in Rails 3 (20)

Adopting DLM at Greentube
Adopting DLM at GreentubeAdopting DLM at Greentube
Adopting DLM at Greentube
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
jQuery Tips'n'Tricks
jQuery Tips'n'TricksjQuery Tips'n'Tricks
jQuery Tips'n'Tricks
 
(WS11) Nikola Plejić: jQuery tips & tricks
(WS11) Nikola Plejić: jQuery tips & tricks(WS11) Nikola Plejić: jQuery tips & tricks
(WS11) Nikola Plejić: jQuery tips & tricks
 
Rails 3.1 Asset Pipeline
Rails 3.1 Asset PipelineRails 3.1 Asset Pipeline
Rails 3.1 Asset Pipeline
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)
 
Rails and security
Rails and securityRails and security
Rails and security
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기
 
JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4JavaScript 2.0 in Dreamweaver CS4
JavaScript 2.0 in Dreamweaver CS4
 
Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Ruby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracksRuby on Rails from the other side of the tracks
Ruby on Rails from the other side of the tracks
 
HTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web ApplicationsHTML5: Building the Next Generation of Web Applications
HTML5: Building the Next Generation of Web Applications
 
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...
A importância dos dados em sua arquitetura... uma visão muito além do SQL Ser...
 
Unleashing the Rails Asset Pipeline
Unleashing the Rails Asset PipelineUnleashing the Rails Asset Pipeline
Unleashing the Rails Asset Pipeline
 
Intro to jQuery
Intro to jQueryIntro to jQuery
Intro to jQuery
 
Better front-end development in Atlassian plugins
Better front-end development in Atlassian pluginsBetter front-end development in Atlassian plugins
Better front-end development in Atlassian plugins
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

UJS in Rails 3

  • 1. UJS in Rails 3 Tuesday, February 1, 2011
  • 2. UJS in Rails 3 by Phil Crissman Tuesday, February 1, 2011
  • 3. Rails and Javascript Tuesday, February 1, 2011
  • 4. Rails and Javascript Javascript helpers have been built into Rails from the very earliest versions. Prototype and Ajaxy helpers have traditionally been “just there” and have always “just worked” Tuesday, February 1, 2011
  • 5. Rails and Javascript Javascript helpers have been built into Rails from the very earliest versions. Prototype and Ajaxy helpers have Magic traditionally been “just there” and have always “just worked” Tuesday, February 1, 2011
  • 9. Unobtrusive Javascript Unobtrusive Javascript is simply the idea of keeping your behavior-defining script out of your content. It’s the same idea as keeping your style- defining rules (CSS) out of your content. Tuesday, February 1, 2011
  • 10. Unobtrusive Javascript So instead of: <a href="#" onclick="alert('ok!');"> Hey </a> We would do: <a href="#" class="alerty"> Hey </a> ... <script type="javascript"> $(function(){ $('.alerty').click(function(){ alert('ok!'); }); }); </script> Tuesday, February 1, 2011
  • 11. Unobtrusive Javascript Is ‘unobtrusive’ Javascript ‘better’? Tuesday, February 1, 2011
  • 12. Unobtrusive Javascript Is ‘unobtrusive’ Javascript ‘better’? Tuesday, February 1, 2011
  • 13. Unobtrusive Javascript Is ‘unobtrusive’ Javascript ‘better’? WELL, THAT’S JUST, LIKE YOUR OPINION MAN Tuesday, February 1, 2011
  • 14. Unobtrusive Javascript Making Javascript ‘unobtrusive’ won’t magically make your code any better. But... Tuesday, February 1, 2011
  • 15. Unobtrusive Javascript It’s ‘better’ in the same sense that separating style from content is ‘better’. Tuesday, February 1, 2011
  • 16. Unobtrusive Javascript And it’s how Javascript helpers are handled by default in Rails 3. Tuesday, February 1, 2011
  • 17. Unobtrusive Javascript In the past, if you wanted to use unobtrusive javascript techniques in Rails, you simply stopped using the built-in Javascript helpers... And wrote all your Javascript from scratch. Tuesday, February 1, 2011
  • 18. Unobtrusive Javascript In Rails 3, you get to keep using the built-in Javascript helpers... And still write all your Javascript from scratch. Tuesday, February 1, 2011
  • 19. Unobtrusive Javascript In Rails 3, you get to keep using the built-in Javascript helpers... And still write all your Javascript from scratch. Tuesday, February 1, 2011
  • 20. UJS in Rails 3 Tuesday, February 1, 2011
  • 21. UJS in Rails 3 Rails 3 makes several changes to the Javascript helpers: Tuesday, February 1, 2011
  • 22. UJS in Rails 3 Rails 3 makes several changes to the Javascript helpers: 1. Instead of inserting inline JS, Rails 3 uses HTML5 data- attributes. Tuesday, February 1, 2011
  • 23. UJS in Rails 3 Rails 3 makes several changes to the Javascript helpers: 1. Instead of inserting inline JS, Rails 3 uses HTML5 data- attributes. 2. No more ‘remote’ helpers (link_to_remote, remote_form_for, et al., are gone). Tuesday, February 1, 2011
  • 24. UJS in Rails 3 Rails 3 makes several changes to the Javascript helpers: 1. Instead of inserting inline JS, Rails 3 uses HTML5 data- attributes. 2. No more ‘remote’ helpers (link_to_remote, remote_form_for, et al., are gone). 3. It’s a lot easier to pull out Prototype and switch to jQuery or mootools, etc, if you want to. Tuesday, February 1, 2011
  • 25. UJS in Rails 3 1. Data attributes. Rails takes advantage of a new feature of HTML5: any tag can have any number of attributes prepended with “data-”, and still be perfectly valid markup. Tuesday, February 1, 2011
  • 26. UJS in Rails 3 Common use case: deleting something, via a link: <%= link_to "Delete", posts_path(@post), :method => "delete", :confirm => "Are you sure?" %> Tuesday, February 1, 2011
  • 27. UJS in Rails 3 Would render (pre Rails 3) as: <a href="/posts/1" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild (m);var s = document.createElement('input'); s.setAttribute ('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'nMxiiHBFyQr9Q3Jc7QGzSd1tk08ujbsHhtF3S26k/k8='); f.appendChild (s);f.submit(); };return false;">Delete</a> Tuesday, February 1, 2011
  • 28. UJS in Rails 3 Would render as: <a href="/posts/1" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild Magic (m);var s = document.createElement('input'); s.setAttribute ('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'nMxiiHBFyQr9Q3Jc7QGzSd1tk08ujbsHhtF3S26k/k8='); f.appendChild (s);f.submit(); };return false;">Delete</a> Tuesday, February 1, 2011
  • 29. UJS in Rails 3 In Rails 3, this same link_to statement... <%= link_to "Delete", posts_path (@post), :method => "delete", :confirm => "Are you sure?" %> ...will render as: <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Delete</a> Tuesday, February 1, 2011
  • 30. UJS in Rails 3 In Rails 3, this same link_to statement... <%= link_to "Delete", posts_path (@post), :method => "delete", :confirm => "Are you sure?" %> ...will render as: <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Delete</a> Tuesday, February 1, 2011
  • 31. UJS in Rails 3 ‘data-method’ and ‘data-confirm’ attributes (and everything else) are handled from /public/javascripts/rails.js // from the jQuery version of rails.js: function allowAction(element) { var message = element.attr('data-confirm'); return !message || (fire(element, 'confirm') && confirm (message)); } Tuesday, February 1, 2011
  • 32. UJS in Rails 3 2. ‘remote’ helpers. Instead of helpers like link_to_remote, in Rails 3, :remote is a param that you include with your link or your form. Tuesday, February 1, 2011
  • 33. UJS in Rails 3 So if we want to make our delete link ajaxy: <%= link_to "Delete", posts_path (@post), :method => "delete", :confirm => "Are you sure?", :remote => true %> Tuesday, February 1, 2011
  • 34. UJS in Rails 3 So if we want to make our delete link ajaxy: <%= link_to "Delete", posts_path (@post), :method => "delete", :confirm => "Are you sure?", :remote => true %> Tuesday, February 1, 2011
  • 35. UJS in Rails 3 This will render (you guessed it) as: <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Delete</a> Tuesday, February 1, 2011
  • 36. UJS in Rails 3 This will render (you guessed it) as: <a href="/posts/1" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Delete</a> And clicking on it will fire a function in rails.js which creates an XMLHttpRequest and sends it to the URL in your href attribute. Tuesday, February 1, 2011
  • 37. UJS in Rails 3 3. Replacing Prototype with jQuery, mootools, or... Rails 3 has made this very simple. Tuesday, February 1, 2011
  • 38. UJS in Rails 3 If we want to use jQuery, for example, we simply add to our Gemfile: gem 'jquery-rails' And then (in the terminal) : % bundle install % rails g jquery:install Tuesday, February 1, 2011
  • 39. UJS in Rails 3 Side note: RJS If you use RJS, just adding jquery-rails does not (at the moment, at least) provide jQuery equivalents for RJS statements. You may be able to use jrails, which does (or at least did) provide these. (I haven’t tried this.) Otherwise, you’ll want to stick with Prototype. Tuesday, February 1, 2011
  • 40. UJS in Rails 3: an example Tuesday, February 1, 2011
  • 41. UJS in Rails 3: an example Let’s actually make it work. Even if not using RJS, there are still a couple ways we can respond to the xhr sent by our delete link. Tuesday, February 1, 2011
  • 42. UJS in Rails 3: an example 1. You could write a javascript template; for a destroy action, this might be destroy.js.erb (or destroy.js.haml)... Tuesday, February 1, 2011
  • 43. UJS in Rails 3: an example This might look something like: / destroy.js.haml $("#posts").html("#{escape_javascript(render (@posts))}"); Tuesday, February 1, 2011
  • 44. UJS in Rails 3: an example 2. Or, you might write javascript hooks straight into application.js, which will be called at the appropriate time. Tuesday, February 1, 2011
  • 45. UJS in Rails 3: an example In public/javascripts/application.js: $(function(){ $('#posts a').bind("ajax:complete", function (n, xhr){ $(this).parent().parent().fadeOut(4000); }); }); Tuesday, February 1, 2011
  • 46. UJS in Rails 3: an example There are several events fired with each xhr (they differ slightly between the Prototype and jQuery version of rails.js): // Prototype rails.js // jQuery rails.js ajax:before ajax:beforeSend ajax:success ajax:success ajax:complete ajax:complete ajax:failure ajax:error ajax:after Tuesday, February 1, 2011
  • 47. Obtrusive Javascript But, if you’re determined to cling to the past: Tuesday, February 1, 2011
  • 48. Obtrusive Javascript But, if you’re determined to cling to the past: Tuesday, February 1, 2011
  • 50. Recap: Rails has a long history of tightly integrating Javascript view helpers; Rails 3 continues this. Tuesday, February 1, 2011
  • 51. Recap: Rails has a long history of tightly integrating Javascript view helpers; Rails 3 continues this. However, in Rails 3, these helpers aim to be unobtrusive. Tuesday, February 1, 2011
  • 52. Recap: Rails has a long history of tightly integrating Javascript view helpers; Rails 3 continues this. However, in Rails 3, these helpers aim to be unobtrusive. Rails 3 js changes include: 1. Utilizing HTML5 data-* attributes. 2. Adding a :remote param to helpers that can use it. 3. Making it easy to drop in alternate JS frameworks in place of Prototypejs. Tuesday, February 1, 2011
  • 53. Recap: Rails has a long history of tightly integrating Javascript view helpers; Rails 3 continues this. However, in Rails 3, these helpers aim to be unobtrusive. Rails 3 js changes include: 1. Utilizing HTML5 data-* attributes. 2. Adding a :remote param to helpers that can use it. 3. Making it easy to drop in alternate JS frameworks in place of Prototypejs. You can either use a js template to send js right back to the browser, or you can take advantage of the ajax hooks provided by rails.js. Tuesday, February 1, 2011
  • 54. Resources: There are several books recently or soon-to-be published covering Rails 3; most seem to have little or no coverage of unobtrusive JS. Tuesday, February 1, 2011
  • 55. Resources: Rails 3 in Action, by Yehuda Katz (@wycats) and Ryan Bigg (@ryanbigg), will contain some examples of UJS. It’s not complete yet, but if you’re interested in checking it out (http://manning.com/katz/), there is a discount code (50% off; valid Jan 23 to Feb 23): rails350 Tuesday, February 1, 2011
  • 56. Resources: Otherwise, your best bet seems to be searching for blog posts and reading the Rails 3 source (particularly rails.js). Tuesday, February 1, 2011
  • 58. railroad closeup: http://www.flickr.com/photos/ericrice/25207672/sizes/m/in/photostream/ railroad clock: http://www.flickr.com/photos/dougtone/4127322153/sizes/z/in/photostream/ train picture: http://www.flickr.com/photos/eterno_retorno/2383602431/sizes/z/in/photostream/ Tuesday, February 1, 2011