ActionView ActionView ActionView ActionView Michael Brunner & Sebastian Knott B-IT International Program of Excellence, Agile Fall 2008 Preparation Seminars, July 31 st , 2008
ActionViewActionViewActionViewActionView
Michael Brunner & Sebastian KnottB-IT International Program of Excellence,Agile Fall 2008 Preparation Seminars,July 31st, 2008
OverviewOverview
ActionViewERB TemplatesERB-TemplatesLayoutsPartialsPartialsHelper MethodsFormsForms
Basic Techniques and AJAXBasic Techniques and AJAXPrototypeScript.aculo.usp
Summaryy
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20082
ActionViewActionView
Template SystemView layer in MVC ControllerView layer in MVCTo include dynamic content
T l t E i
ModelView
Template EnginesERB-Templates (*.rhtml)XML Markup Templates (* rxml)XML-Markup-Templates (*.rxml)RJS-Templates (*.rjs)
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20083
ActionView – ERB-Templates 1/2ActionView – ERB-Templates 1/2
Embedded RubyStandard template of RailsStandard template of RailsTags
<% %> execution & no display<% %> execution & no display<%= %> execution & display<% -%> execution & no display (no new line)<% -%> execution & no display (no new line)<%# %> comment
<% for employee in @employees %><tr>
<td><%= employee.firstname %></td>td % l l t % /td<td><%= employee.lastname %></td>
</tr><% end %>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20084
ActionView – ERB-Templates 2/2ActionView – ERB-Templates 2/2
AdvantagesFlexibleFlexibleAll kinds of text files can be generatedSimilar to PHPSimilar to PHP
DisadvantagesDisadvantagesMixed programming languagesHard to readHard to read
All Ruby commands are executableAll Ruby commands are executableLiquid Templates
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20085
ActionView – Layouts 1/3ActionView – Layouts 1/3
Regular used design can be moved into layout filesapp/views/layoutsapp/views/layouts
Support DRY-PrincipleController variables are available in the layout fileController variables are available in the layout file
application rhtml is used by all viewsapplication.rhtml is used by all views<controller>.rhtml is used by the controller
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20086
ActionView – Layouts 2/3ActionView – Layouts 2/3
<html xmlns=http://www.w3.org/1999/xhtml xml:lang="en" lang="en"><head>
% i ld h d %<%= yield :head %></head><body>
<p style="color: green"><%= flash[:notice] %></p>% i ld %<%= yield %>
</body></html>
% t t f h d d %<% content_for :head do %><%= stylesheet_link_tag “projects” %>
<% end %>
R t
yield
Rest …
yIn layout fileTo include the view templatesp
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20087
ActionView – Layouts 3/3ActionView – Layouts 3/3
layout template_name[, conditions]
To specify the layout to be usedTo specify the layout to be usedclass EmployeesController < ApplicationController
layout "admin“ # applies app/views/layouts/admin.rhtmll t " d i " l [ dit ] # l f dit ht l d ht llayout "admin", :only => [:edit, :new] # only for edit.rhtml and new.rhtml.layout "admin", :except => :index # not for index.rhtml in app/views/employees/
layout :user_layout # applies app/views/layouts/admin.rhtml or# / i /l t / li ti ht l# app/views/layouts/application.rhtml
protecteddef user_layout
if current_user.admin?“ d i ”“admin”
else“application”
enddend
end
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20088
ActionView – Partials 1/4ActionView – Partials 1/4
Sub templateFile name with leading underscoreFile name with leading underscore
render :partial => “partial”,
:locals => {:<var> => “var”, …}
app/views/employees/edit.rhtml<h1>Editing employee</h1>
<%= render :partial => "form",:locals => {:submit text => “Edit"}
<% form_for @employee do |f| %><p>
% f l b l titl “Titl " % b /
app/views/employees/_form.rhtml
:locals {:submit_text Edit }%>
<h1>New employee</h1>app/views/employees/new.rhtml
<%= f.label :title => “Title" %><br />...
</p> <p>
% f b it b it t t % h1 New employee /h1
<%= render :partial => "form",:locals => {:submit_text => “Create"}
%>
<%= f.submit submit_text %></p>
<% end %>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 20089
%
ActionView – Partials 2/4ActionView – Partials 2/4
Partials with CollectionTo perform actions on resourcesTo perform actions on resources
<% for ad in @advertisements %>@<%= render :partial => "ad",
:locals => { :ad => ad } %>
<% end %>
is replaced by<%= render :partial => "ad",p ,
:collection => @advertisements%>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200810
ActionView – Partials 3/4ActionView – Partials 3/4
render :partial => “partial”, :collection => @array:collection => @array,[:spacer_template => “space”]
<div><p>
app/views/employees/_employee.rhtml<h2>Mitarbeiter Details</h2>app/views/employees/show.rhtml
<p><b>Firstname:</b><%= employee.firstname %>
</p><p>
<%= render :partial => “employee”,:collection = > @employees,:spacer_template => "space"
%> <p><b>Lastname:</b><%= employee.lastname %>
</p></div>
%>
app/views/employees/_space.rhtml<hr /> </div><hr />
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200811
ActionView – Partials 4/4ActionView – Partials 4/4
Shared PartialsUsually in app/views/sharedUsually in app/views/shared
<%= render :partial => "shared/copyright" %>
Layout PartialsAssigning a layout to a partialAssigning a layout to a partialSaved next to the corresponding partialyield to import the corresponding partialyield to import the corresponding partial
<div id="copyright">% i ld %
app/views/shared/_copyright_full.rhtml<h1>List of Employees</h1>app/views/employees/index.rhtml
<%= yield %><p>All Rights reserved</p>
</div>
...<%= render :partial => "shared/copyright",
:layout => "shared/copyright_full"%>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200812
Helper MethodsHelper Methods
As little Ruby code as possibleNo programming logic in templatesNo programming logic in templatesCalculations in helper methods
H l O iHelper OverviewNumberHelperTextHelper
SantizeHelperUrlHelperTextHelper
TagHelperAssetTagHelper
UrlHelperCustom Helper
AssetTagHelper
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200813
Helper Methods – NumberHelper 1/2Helper Methods – NumberHelper 1/2
number_to_currency (number[, options])precision (2) unit ($) separator ( ) delimiter ( )precision (2), unit ($), separator (.), delimiter (,), format (%u%n)
number to currency (1000.129)number_to_currency (1000.129)# => $1,000.13
number_to_currency (1000.129, :precision => 4, :unit => “€”, :separator => “,”, :delimiter => “.”, :format => "%n %u")
number_to_human_size (bytes[, precision(<=1)])
:delimiter . , :format %n %u )# => 1.000,1290 €
number_to_human_size (1500)# => 1.5 KB
number to human size (1048576)number_to_human_size (1048576)# => 1 MB
number_to_human_size (2000000000, 2)# => 1 86 GB
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200814
# => 1.86 GB
Helper Methods – NumberHelper 2/2Helper Methods – NumberHelper 2/2
number_with_delimiter (number[, options])delimiter ( ) separator ( )delimiter (,), separator (.)
number_with_delimiter (1240.99)# => 1,240.99
number_with_delimiter (1240.99, “.”, “,”)# => 1.240,99
number_with_precision (number[, precision(3)])b ith i i (1240 4567)number_with_precision (1240.4567)
# => 1,240.457
number_with_precision (1240.4567, 2)# 1 240 46# => 1.240,46
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200815
Helper Methods – TextHelper 1/2Helper Methods – TextHelper 1/2
highlight (text, phrase[, highlighter(<strong class="highlight">\1</strong>)])class= highlight >\1</strong>)])
highlight('You searched for: rails', 'rails') # => You searched for: <strong class="highlight">rails</strong>
highlight('You searched for: rails', ['for', 'rails'], '<em>\1</em>') # => You searched <em>for</em>: <em>rails</em>
highlight('You searched for: rails', 'rails', "<a href='search?q=\1'>\1</a>")
word_wrap(text[, length(80)])
g g t( ou sea c ed o a s , a s , a e sea c q \ \ /a )# => You searched for: <a href='search?q=rails’>rails</a>
word_wrap('Once upon a time') # => Once upon a time
word wrap('Once upon a time', 8)word_wrap( Once upon a time , 8) # => Once upon\na time
word_wrap('Once upon a time', 1) # => Once\nupon\na\ntime
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200816
p
Helper Methods – TextHelper 2/2Helper Methods – TextHelper 2/2
truncate (text[, length(30), t_str(“…”)])truncate("Once upon a time in a world far far away")truncate( Once upon a time in a world far far away ) # => Once upon a time in a world f...
truncate("Once upon a time in a world far far away", 14, "... (continued)") # => Once upon a (continued)
markdown(text)P k Bl Cl th t b i t ll d
# => Once upon a ... (continued)
Package BlueCloth must be installedmarkdown("We are using __Markdown__ now!") # => <p>We are using <strong>Markdown</strong> now!</p>
textilize(text)Package RedCloth must be installedPackage RedCloth must be installed
textilize("*This is Textile!* Rejoice!") # => <p><strong>This is Textile!</strong> Rejoice!</p>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200817
Helper Methods – TagHelperHelper Methods – TagHelper
tag(name[, options, open(false), escape(true)])XHTML or HTML 4 0 compatibleXHTML or HTML 4.0 compatible
tag (“br”) # XHTML compatible# => <br />
(“ ) #tag (“br”, nil, true) # HTML 4.0 compatible# => <br>
tag (“input”, {:type => ‘text’, :disabled => true})# => <input type=“text” disabled=“disabled”>
content_tag(name[, content, options, escape(true)])Attribute values can be true instead of disabled/readonly
# => <input type= text disabled= disabled >
Attribute values can be true instead of disabled/readonlycontent_tag(:p, "Hello world!“) # => <p>Hello world!</p>
content_tag("select", options, :multiple => true) # => <select multiple="multiple">...options...</select>
<% content_tag :div, :class => "strong" do -%> Hello world! <% end -%>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200818
# => <div class="strong"><p>Hello world!</p></div>
Helper Methods – AssetTagHelper 1/2Helper Methods – AssetTagHelper 1/2
javascript_include_tag *sources[, html-options]defaults (register javascript include default)defaults (register_javascript_include_default)all (javascript/)cache (ActionController::Base perform caching = true)cache (ActionController::Base.perform_caching true)
javascript_include_tag "common.javascript.js", "http://www.railsapplication.com/xmlhr" # => <script type="text/javascript" src="/javascripts/common javascript"></script># => <script type= text/javascript src= /javascripts/common.javascript ></script>
<script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js"></script>
javascript_include_tag :defaults# => <script type="text/javascript" src="/javascripts/prototype js"></script># > <script type text/javascript src /javascripts/prototype.js ></script>
<script type="text/javascript" src="/javascripts/effects.js"></script> ...<script type="text/javascript" src="/javascripts/application.js"></script>
javascript_include_tag :all :cache => true# => <script type="text/javascript" src="/javascripts/all.js"></script>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200819
Helper Methods – AssetTagHelper 2/2Helper Methods – AssetTagHelper 2/2
stylesheet_link_tag *sources[,html-options]all (stylesheets/)all (stylesheets/)cache (ActionController::Base.perform_caching = true)
stylesheet_link_tag "style.css" , "http://www.railsapp.com/style" # => <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="http://www.railsapp.com/style.css" media="screen" rel="stylesheet" type="text/css" />
stylesheet_link_tag "style", {:media => "all“, :class => “css”} # => <link href="/stylesheets/style.css" class=“css” media="all" rel="stylesheet" type="text/css" />
stylesheet link tag :allstylesheet_link_tag :all # => <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
…<link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
stylesheet_link_tag :all, :cache => true# => <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200820
Helper Methods – SanitizeHelperHelper Methods – SanitizeHelper
strip_links (text)
strip tags ( )
strip_links('Please e-mail me at <a href="mailto:[email protected]">[email protected]</a>.') # => Please e-mail me at [email protected].
strip_tags (text)strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...<!-- link -->") # => Bold no more! See more here... link
h(text)
# Bold no more! See more here... link
h("<b>Bold</b> no more!") # => <b>Bold</b> no more!
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200821
Helper Methods – UrlHelper 1/2Helper Methods – UrlHelper 1/2
link_to name[, options, html_options]anchor (nil) query (nil) only path (true) trailing slashanchor (nil), query (nil), only_path (true), trailing_slash (false), host (nil), protocol (nil), user (nil), password (nil), escape (true)method (GET), popup (false), confirm (nil)
link to "Profiles" “/profiles"link_to Profiles , /profiles# => <a href="/profiles">Profiles</a>
link_to "Profile", profile_path(@profile) # => <a href="/profiles/1">Profile</a>
link_to "Profile", @profile# => <a href="/profiles/1">Profile</a>
link_to "Comment wall", profile_path(@profile, :anchor => "wall"), :class => “comment"# => <a href="/profiles/1#wall“ class=“comment“>Comment wall</a>
link_to "Help", {:controller => “testing” :action => "help“}, :popup => true # => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200822
Helper Methods – UrlHelper 2/2Helper Methods – UrlHelper 2/2
button_to (name[, options, html_options])anchor (nil) only path (true) trailing slash (false) hostanchor (nil), only_path (true), trailing_slash (false), host (nil), protocol (nil), user (nil), password (nil), escape (true)method (POST), disabled (false), confirm (nil)( ), ( ), ( )
button_to "New", :action => "new"# => <form method="post" action="/controller/new" class="button-to">p
<div><input value="New" type="submit" /></div> </form>
button_to "Delete Image", { :action => "delete", :id => @image.id }, _ g { @ g }:confirm => "Are you sure?", :method => :delete
# => <form method="post" action="/images/delete/1" class="button-to"><div>
<input type="hidden" name="_method" value="delete" /> <input onclick="return confirm('Are you sure?');" value="Delete" type="submit" />
</div> </form>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200823
Helper Methods – Custom HelperHelper Methods – Custom Helper
app/helpers/<controller>_helper.rbCustom Helper ModulesCustom Helper ModulesAll helper files are loaded automatically
Modify helper :all in app/controllers/application rb toModify helper :all in app/controllers/application.rb to change behavior
<h1>New employee</h1><%= error_messages_for :employee %>
app/views/employees/new.rhtmlmodule EmployeesHelper
def back to list
app/helpers /employees_helper.rb
_ g _ p y
<% form_for @employee do |f| %>...
<% end %>
_ _link_to “Back to List", employees_path
endend
<%= back_to_list %>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200824
ActionView – Forms 1/6ActionView – Forms 1/6
Rails provides a fully integrated form i t finterfaceForms provide access to application dataForms may be mapped directly to the database
... by convention or by the user.
Helper methodsHelper methods Construct HTML-FormsHandle dynamic requestsHandle dynamic requests
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200825
ActionView – Forms 2/6ActionView – Forms 2/6
Rails Webserver
myapp_controller.rb(Controller)
Client
Generated F
edit.rhtml(Template)
Form
(Template)
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200826
ActionView – Forms 3/6ActionView – Forms 3/6
def newmyapp_controller.rbdef new
@product = Product.newend
def createdef create@product = Product.new(params[:product])…
end
Controller actions forR d i th fRendering the formProcess the data returned by the form
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200827
ActionView – Forms 4/6ActionView – Forms 4/6
<% form for :product :url => { :action => :create } do |form| %>edit.rhtml<% form_for :product, :url => { :action => :create } do |form| %>
<p>Title: <%= form.text_field :title, :size => 30 %></p><p>Description: <%= form.text_area :description, :rows => 3 %></p><p>Image URL: <%= form.text_field :image_url %></p><p>Price: <%= form text field :price :size => 10 %></p>
f f h l t HTML f d th
<p>Price: <%= form.text_field :price, :size => 10 %></p><p><%= submit_tag %></p>
<% end %>
form_for helper generates HTML-form and gathers data for
Data type: productData type: productController action: create
text field and text area helper generate HTML Inputtext_field and text_area helper generate HTML-Input fields
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200828
ActionView – Forms 5/6ActionView – Forms 5/6
<form action="/form_for/create" method="post" >Titl
edit.rhtml
<p>Title: <input id="product_title" name="product[title]" size="30" type="text" />
</p><p>Description:
t t id "d i ti " " d t[d i ti ]" "3" /<textarea id="description" name="product[description]" rows="3" /></p><p>Image URL:
<input id="image_url" name="product[image_url]" size="30" type="text" /></ ></p><p>Price:
<input id="price" name="product[price]" size="30" type="text" /></p>
</f >
Names and ids will be set by the helpersf
</form>
Rails provides helpers for each input tagAll helpers require at least on parameter
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200829
ActionView – Forms 6/6ActionView – Forms 6/6
Advanced TechniquesMultiple models in one formMultiple models in one formCustom Form BuildersDynamic FormsDynamic Forms
Auto completionAdaptive FormsAsynchronous Data SubmissionError Handling
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200830
Basic Techniques and AJAXBasic Techniques and AJAX
HTMLCSSCSSJavaScriptDOMDOMAJAX
P t tPrototypeScript.aculo.us
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200831
HTML – Hypertext Markup Language 1/3HTML – Hypertext Markup Language 1/3
Basis of the ser<html>
<head>titl Titl /titlBasis of the user
interfaceInterpreted by a local
<title>Title</title></head><body>
Lorem ipsum dolor sit amet, t t di i lit d diInterpreted by a local
client (Browser) XML like Syntax
consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
</body></ht l>XML-like Syntax
TagsAttributes
</html>
Attributes
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200832
HTML – Hypertext Markup Language 2/3HTML – Hypertext Markup Language 2/3
Provides structure to<html>
<head> Provides structure to a textB i t li
<title>Title</title></head><body>
Lorem ipsum <b>dolor</b> sit amet, Basic styling Additional interactive
consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna <a href=“index.html”> aliquyam </a>
components</body></html>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200833
HTML – Hypertext Markup Language 3/3HTML – Hypertext Markup Language 3/3
Embedding of M di fil
<html><head> Media files
ImagesFlash
<head><title>Title</title><link rel=“stylesheet” type=“text/css”
href=“formats.css”><script type=“text/javascript”> Flash
ScriptsJavaScripts
<script type= text/javascript ><!-- alert(“Hello World!”) -->
</script><script src=“square.js” type=“text/javascript”></script>
</head> JavaScriptsColdfusion
Stylesheets
</head><body>
Lorem ipsum dolor sit amet, consetetur sadipscingelitr, sed diam nonumy eirmod tempor invidunt utlabore et dolore magna aliquyam y
CSSlabore et dolore magna aliquyam
</body></html>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200834
CSS – Cascading Style Sheets 1/4CSS – Cascading Style Sheets 1/4
Body { color: black;}#globalWrapper { font-size:127%;}HR, MENU, PRE { display: block }H5.big { font-size: .83em;
line-height: 1.17em; margin: 1.67em 0
}
St l h t l t l t th t ti
}:focus { float: right }A:link { voice-family: harry, male }
Stylesheet language to supplement the presentation of a documentCommonly used to aggregate the style informationCommonly used to aggregate the style-information and further specify the layoutAbstraction of the document design from theAbstraction of the document design from the document structure
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200835
CSS – Cascading Style Sheets 2/4CSS – Cascading Style Sheets 2/4
First limited support of CSS1 in IExplorer3 released in 19961996Near-full implementation in 2000October 31, 2005 first browser passes the ACID2 testp
Safari 2.0.2Until today no Browser fully implements CSS2
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200836
CSS – Cascading Style Sheets 3/4CSS – Cascading Style Sheets 3/4
Key features CSS1Unique identification and generic classification byUnique identification and generic classification by class, id and tagFont properties (e.g. emphasis, typeface)p p ( g p , yp )Color properties Text attributes (e.g. spacing) Alignment of elementsMargin, padding, border, positioning
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200837
CSS – Cascading Style Sheets 3/4CSS – Cascading Style Sheets 3/4
Key features CSS2Absolute relative and fix positioningAbsolute, relative and fix positioningMedia typesAural style sheetsAural style sheetsBidirectional textNew font propertiesNew font properties
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200838
JavaScript 1/4JavaScript 1/4
JavaScript developed by
function $type(obj){ if (!$defined(obj)) return false; if (obj.htmlElement) return 'element'; var type = typeof obj; developed by
Brendan Eich of Netscape
yp yp j;
if (type == 'object' && obj.nodeName){ switch(obj.nodeType){
case 1: return 'element'; case 3: return (/\S/) test(obj nodeValue) ? 'textnode' :Netscape
Contrary to popular b li f l d
case 3: return (/\S/).test(obj.nodeValue) ? textnode : 'whitespace';
} }
if (t ' bj t' || t 'f ti '){belief not related to Java
if (type == 'object' || type == 'function'){ switch(obj.constructor){
case Array: return 'array'; case RegExp: return 'regexp'; case Class: return 'class';
Lightweight client-side script language
}
if (typeof obj.length == 'number'){ if (obj.item) return 'collection'; if (obj callee) return 'arguments';
Designed to look like Java
if (obj.callee) return arguments ; }
}
return type; }
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200839
};
JavaScript 2/4JavaScript 2/4
FeaturesWeakly typedWeakly typedObject-basedDynamicDynamicRuns in a “sandbox”
Most commonly used embedded in web browsersInternet Explorer 3+
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200840
JavaScript 3/4JavaScript 3/4
What JavaScript doesPost process HTMLPost-process HTML
Dynamic documentsControlling the browser (within certain limits)Controlling the browser (within certain limits)Extract some information about browser and operation systemOpen asynchronous connections to serverAccess the DOM
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200841
JavaScript 4/4JavaScript 4/4
IssuesMi ft J i tMicrosoft Jscript
„Almost the same“
XSS and otherXSS and other security related issuesissuesAdblocker, NoScript, etc.
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200842
DOM – Document Object Model 1/2DOM – Document Object Model 1/2
Standard object model for XML-like formatsPlatform system and language independentPlatform-, system- and language independentProvides a model for standardized access to HTML-DocumentsDocumentsFirst introduced by W3C in October 1998
Bundled with HTML 4Bundled with HTML 4By now browser developers compete for the strictest and most advanced implementationand most advanced implementation
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200843
DOM – Document Object Model 2/2DOM – Document Object Model 2/2
<table><thead>
<tr>th Fi t N /th<th>First Name</th>
<th>Last Name</th></tr>
</thead><tb d ><tbody>
<tr><td>Donald</td><td>Duck</td>
</t ></tr></tbody>
</table>
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200844
AJAX – Asynchronous JavaScript and XML 1/3AJAX – Asynchronous JavaScript and XML 1/3
The basis of all Web2.0Key functionality XMLHttpRequestKey functionality XMLHttpRequest Asynchronous data traffic between Server and BrowserBrowser
HTMLJSONJSONXML
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200845
AJAX – Asynchronous JavaScript and XML 2/3AJAX – Asynchronous JavaScript and XML 2/3
Web1.0 Web2.0
Webserver Webbrowser Webserver Webbrowser
*click*
*click*
No Userinterface
*click*
*click*
Incomplete UI
Complete UI
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200846
AJAX – Asynchronous JavaScript and XML 3/3AJAX – Asynchronous JavaScript and XML 3/3
Prosff
ConsLess trafficFaster response
No integration with browsers navigation engineNo 3rd party
software
engine „Back“-buttonBookmarksBookmarks
Enforces JavaScript
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200847
AJAX and RailsAJAX and Rails
Prototype script.aculo.usDevelopment tools
ShortcutsE t i
Dynamic visual effectsSt d d GUIExtensions
UtilitiesSt d d li t
Standard GUI-elements
ControlsStandards-compliantEases the pain out of cross browser
ControlsBehaviours
Compact syntaxof cross-browser development
Compact syntax
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200848
AJAX – Prototype 1/2AJAX – Prototype 1/2
Shortcuts$()for selecting elements by ID$()for selecting elements by ID
Chaining$$() for selecting elements by CSS filter$F() for extraction values of input fields
ExtensionsString replacement by String.gsub
Search by regex or fixed stringR l t ttReplacement patterns
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200849
AJAX – Prototype 2/2AJAX – Prototype 2/2
UtilitiesAJAX bj t function searchSales(){AJAX objects
Automated XMLHttpRequest
function searchSales(){ var empID = $F('lstEmployees'); var y = $F('lstYears'); var url = 'http://yourserver/get'; var pars = 'empID='+ y;XMLHttpRequest
generationonSuccess onFailure h dli
var pars empID y;
var myAjax = new Ajax.Request( url, { method: 'get', handling
Automated replacement of HTML-
{ g ,parameters: pars, onComplete: showResponse }
); } p
content Evaluate Javascript
}
function showResponse(originalRequest){ //put returned XML in the text area $('result').value = originalRequest.responseText; $( ) g q p ;
}
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200850
AJAX – Script.aculo.us 1/2AJAX – Script.aculo.us 1/2
Visual effects BehaviorsHighlightMorph
DraggableDroppable
MoveOpacity
SortableControls
ScaleParallel
Ajax.InPlaceEditorAjax.Autocompleter
QueuesAjax.AutocompleterBuilder
Demos
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200851
AJAX – Script.aculo.us 2/2AJAX – Script.aculo.us 2/2
element = Builder.node('div',{id:'ghosttrain'},[ Builder node('div' {className:'controls'
Compact codeBuilder.node( div ,{className: controls ,
style:'font-size:11px'},[ Builder.node('h1','Ghost Train'), "testtext", 2, 3, 4, Builder node('ul' [
Easy to useCompatible
new Effect.Fade('id_of_element');
new Effect.Fade('id_of_element', { d ti 2 0 f 0 0 t 0 8 })
Builder.node( ul ,[ Builder.node('li',{className:'active',
onclick:'test()'},'Record') ])
]){ duration:2.0, from:0.0, to:0.8 });
<div id="ghosttrain">
]) ]);
B ild <div class="controls" style="font-size:11px"><h1>Ghost Train</h1>testtext234<ul>
BuilderHTML out of thin
i <li class="active" onclick="test()">Record</li></ul>
</div></div>
air
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200852
SummarySummary
ActionViewTemplate System corresponding to the view in MVCTemplate System corresponding to the view in MVC
LayoutsUsed to extract common designUsed to extract common design
PartialsSub templatesSub templates
Helper MethodsTo reduce the amount of Ruby codeTo reduce the amount of Ruby code
FormsFast and easy HTML-form generationFast and easy HTML form generation
AJAX Dynamic websites and eye candyDynamic websites and eye candy
ActionView, Michael Brunner & Sebastian KnottB-IT International Program of Excellence
31. July 2008Agile Fall 200853