rails 3 beginner to builder 2011 week 4
DESCRIPTION
This is the 4th of 8 presentations given at University of Texas during my Beginner to Builder Rails 3 Class. For more info and the whole series including video presentations at my blog: http://schneems.com/tagged/Rails-3-beginner-to-builder-2011TRANSCRIPT
@Schneems
Did your Homework?• Or promise you will
• (Chapters 8 & 9)
• Grab A Gowalla Tee Shirt!!
• Sizes run a bit small
Thursday, June 30, 2011
June, 2011
Beginner to BuilderWeek 4
Richard Schneeman@schneems
Thursday, June 30, 2011
@Schneems
Rails Hotline• Call them and ask rails questions
• (877)- 817- 4190
• Free
Thursday, June 30, 2011
@Schneems
Rails - Week4• Html, Javascript and CSS
• Error Handling
• begin - rescue - end
• Ajax - “Web 2.0”
• What is it?
• Partials
• Considerations
Thursday, June 30, 2011
@Schneems
HTML• Hyper Text Markup Language
• Used to create Webpages
Thursday, June 30, 2011
@Schneems
HTML <div id="content" class="clearfix">
<h1>Keep up with your friends, share the places you go,<br /> and discover the extraordinary in the world around you.</h1>
<div id="content"> <div id="leather" class="clearfix"> <!-- tour --> <div id="tour">
<div id="tour_inner" style="left: 0px; -webkit-transform: translate3d(0px, 0px, 0);">
<div id="homepage" style="background: transparent url(/images/tour/home-2.png) top left no-repeat;"> <div class="feature friends"> <div class="feature-icon"></div> <p><strong>Keep up with friends on your phone.</strong> Connect with friends from Facebook and Twitter to share where you're going.</p> </div> <div class="feature discover"> <div class="feature-icon"></div> <p><strong>Discover new places and hotspots</strong> when you go out, then share your photos, recommendations and trips with friends!</p> </div> <div class="feature rewards"> <div class="feature-icon"></div> <p><strong>Find inspiration to explore</strong> the world around you while picking up rewards from local eateries, venues and retail stores.</p> </div> </div>
Thursday, June 30, 2011
@Schneems
HTML
Thursday, June 30, 2011
@Schneems
HTML elements• Most elements have start and end
tags
• can have optional attributes<p>This is an element</p>
<br /><!-- so is this -->
<h1 class=”foo”>
This is an element with an attribute
</h1>
Thursday, June 30, 2011
@Schneems
.html.erb• ERB
• Embedded Ruby
• Ruby code that generates HTML
<h1>People</h1>
<ul>
<% @people.each do |person| %>
<li><%= person.first_name %></li>
<% end -%>
</ul>
<h1>People</h1>
<ul>
<li>Bob</li>
<li>Joe</li>
<li>Mary</li>
</ul>
=>
Thursday, June 30, 2011
@Schneems
.html.erb
<%= "This is an ERB Display Tag " %>
<% foo = "Embedded expression does not render" %>
<% 3.times do |i| %>
<%= "Hello #{i}" %>
<% end %>
Thursday, June 30, 2011
@Schneems
.html.haml• ERB alternative
• Meaningful whitespace
• no “end” keyword%h1
People
%ul
- @people.each do |person|
%li=person.first_name
<h1>People</h1>
<ul>
<li>Bob</li>
<li>Joe</li>
<li>Mary</li>
</ul>
=>
Thursday, June 30, 2011
@Schneems
CSS• Cascading Style Sheets
• Rules Based Style
• Casscade
• What happens if more than one rule is applied?
Thursday, June 30, 2011
• ( # ) id
• ( . ) class
• element
@Schneems
// id selector
#main { background-color: orange;}
// class selector
.sidebar { color: black; }
// element selector
span { font-size: 24px;}
// mixed
span.sidebar { color: #C5C5C5; }
CSS
Thursday, June 30, 2011
@Schneems
CSS• Inline styles
• Embedded style
• External style
Thursday, June 30, 2011
@Schneems
CSS<!-- inline -->
<p style="color:black">tag</p>
<!-- Embedded -->
<style type="text/css">
p {color:black}
</style>
<!-- External -->
<link rel="stylesheet"
type="text/css" href="mystyle.css" />
Thursday, June 30, 2011
@Schneems
CSS• Inheritance
• specificity
• location
Thursday, June 30, 2011
@Schneems
<p>
<span>Hello There</span>
</p>
CSS• Inheritence
p {
color: blue;
}
Thursday, June 30, 2011
@Schneems
CSS• Specificity
* {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
li {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
li:first-line {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul li {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul ol+li {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
h1 + *[rel=up]{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
ul ol li.red {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
li.red.level {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
#x34y {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
Thursday, June 30, 2011
@Schneems
CSS• Location
• Later rules are more important
p {
color: blue;
}
p {
color: red;
}
paragraph will be red
Thursday, June 30, 2011
@Schneems
Browser Wars• Different browsers
• same content
• Different Results
• IE
• Safari
• Chrome
• FireFox
• etc.
Thursday, June 30, 2011
@Schneems
JavaScript• Client Side Scripting Language
• (The web browser is the client)
• Make your websited more dynamic
Java is to JavaScript as Car is to Carpet
var name = prompt("What is your name?");
alert("Welcome " + name);
Thursday, June 30, 2011
@Schneems
Javascript• Can manipulate the DOM
• DOM
• Document Object Model
Thursday, June 30, 2011
@Schneems
DOM
Document Object ModelThursday, June 30, 2011
@Schneems
JavaScript Libraries• Written in JavaScript
• Makes writing JavaScript easier
• jQuery (rails >= 3.1)
• Prototype (rails < 3.1)
Thursday, June 30, 2011
@Schneems
jQuery• The pre-packaged JavaScript library
with rails 3.1
// Javascript
window.document.body.style.display = 'none';
// jQuery
$('body').hide()
Thursday, June 30, 2011
@Schneems
jQuery in Rails 3• Use jQuery gem
gem install "jquery-rails"
rails generate jquery:install
Thursday, June 30, 2011
@Schneems
JavaScript Debugging• Firefox #=> FireBug
• Safari #=> Inspect Element
• Chrome #=> Inspect Element
• IE #=> Don’t ever use IE
Thursday, June 30, 2011
@Schneems
CSS Debugging• Firefox #=> FireBug
• Safari #=> Inspect Element
• Chrome #=> Inspect Element
• IE #=> Don’t ever use IE
Thursday, June 30, 2011
• What is an Exception?
• How can we handle Exceptions
• Rails’ errors attributes
@Schneems
Error Handling
Thursday, June 30, 2011
• What is an Exception?
• A standard ruby object
@Schneems
raise “you entered an invalid attribute”
Error Handling
rubylearning.org
Create with raise
Optionally provide type of exception
raise ArgumentError, "Argument is not numeric"
Thursday, June 30, 2011
@Schneems
raise "bad stuff happened"
Raise• Code confident
• raise errors in truly exceptional situations
• error will be logged
• user will end up seeing a 500 error unless error is handled
Thursday, June 30, 2011
• Begin-Rescue-End (Ruby)
• Like Try - Catch
• Begin attempts to run code
• If exception, then rescue catches the error
@Schneems
begin
dept = Department.find(thisdept)
rescue
"No Department"
end
Error Handling
Thursday, June 30, 2011
• Begin-Rescue-End (Ruby)
• Ensure - Runs regardless of errors
@Schneems
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
rescue
# ... handle the exceptions ...
ensure
file.close # ... and this always happens.
end
Error Handling
Thursday, June 30, 2011
• Begin-Rescue-End (Ruby)
@Schneems
Error Handling
rescue defaults to StandardError
rescue can handle different types of exceptions
rescue Exception will rescue any exception
rescue
rescue SyntaxError
rescue Exception
Thursday, June 30, 2011
• Logger
• Rails logs activity
• {production, development, test}.log
• Useful to see where errors occured
• Use tail to view current activity
@Schneems
$: tail -f logs/production.log
Error Handling
(much better than trying to load a +200mb log file into a text editor)
Thursday, June 30, 2011
• Logger
• Specify different levels of logging details
• Filter out sensitive info from logconfig.log_level = :debug
Now, no passwords will show up in any log file
Keeps hackers in the dark, and SysAdmins honest
@Schneems
config.filter_parameters += [:password]
Error Handling
config/environments/production.rb
config/environment.rb
Thursday, June 30, 2011
• Logger
• Different log levels filtered by logger
@Schneems
config.log_level = :debug
Error Handling
config/environments/production.rb
LevelsExample:
Thursday, June 30, 2011
• Logger
• How do I write something to the log?
• Errors and exceptions added
• call logger directly
@Schneems
logger.error "Something Bad Happened"
Error Handling
Puts info in log without raising error
Thursday, June 30, 2011
• Errors in rails
• Attached to objects
• Access through errors method
• @dog.errors
@Schneems
<% @dog.errors.full_messages.each do |msg| %>
<li><%=raw msg %></li>
<% end %>
Errors in Rails
Thursday, June 30, 2011
• How do we add Errors to objects?
• Pre-Built Validations
• Custom Validations
@Schneems
validate :speed_must_be_divisible_by_three
private
def speed_must_be_divisible_by_three
errors.add(:speed, "Speed is not divisible by three") unless speed%3 == 0
end
Errors in Rails
validates :name, :presence => true, :uniqueness => true
Thursday, June 30, 2011
@Schneems
• What is Ajax
• Asynchronous Javascript
• Doesn't require page reload
Ajax
Maps.google.com Gowalla.com
Thursday, June 30, 2011
@Schneems
• Example:1. Send form data to Controller via JS2. Controller parses form data3. Controller returns info to browser4. browser renders info5. user sees no page reload6. magic!!
Ajax
Thursday, June 30, 2011
@Schneems
Ajax• Considerations
• User Expectations
• Loading...
• Don’t break the back button
• No Javascript?
• Principle of least surprise
Thursday, June 30, 2011
@Schneems
• Loading
• Usually Gif Files
• Doesn't require page reload
• Lets user know “something” is happening
Ajax
Loading...
Thursday, June 30, 2011
@Schneems
• Loading
• Usually Gif Files
• Doesn't require page reload
• Lets user know “something” is happening
Ajax
Loading...
Thursday, June 30, 2011
@Schneems
• Don’t break the back button
•Don’t do it
• Don’t break user copied urls
•Don’t do it
• If you’re doing it
•Don’t (and find a fix)
Ajax
Thursday, June 30, 2011
@Schneems
• What if I’m using IE 5?
• Unobtrusive Javascript
• No reduced Functionality
• Rails 3 Does it
Ajax
Thursday, June 30, 2011
@Schneems
Code Here
• Unobtrusive Javascript
Ajax - In Rails
If no Javascript We Still use Normal Http Request
<% form_tag search_path, :id => "search-form", :remote => true do %>
<span>Username: </span>
<%= text_field_tag 'username' %>
<%= submit_tag 'Submit'%>
<% end %>
<form action="/spot/show" data-remote="true" id="search-form" method="post"> <div> <input name="authenticity_token" type="hidden" value="7+2/AAuZF1X55xdRW0dHtx/7NL6aq8stuhqeQFeaSfI=" /> </div> <span>Username: </span> <input id="username" name="username" type="text" /> <input name="commit" type="submit" value="Submit" /> </form> </div>
Thursday, June 30, 2011
• Okay, so I asynchronously submit stuff, what do I do when I get a response?
• Handle No response case (404,500, etc.)
• Render a format
• Controller responds to different formats
@Schneems
respond_to do |format|
format.html { redirect_to(person_list_url) }
format.json
format.xml { render :xml => @person.to_xml(:include => @company) }
end
Ajax - In Rails
Thursday, June 30, 2011
• Different formats
• Render Different results
@Schneems
render :xml
render :json
render :text => “hey there”
render :js => “alert(‘hello’);”
render :template => “dogs/show”
render :partial => “form”
Ajax - In Rails
Partials?
Thursday, June 30, 2011
@Schneems
Code Here
• Partials
• Reusable html.erb templates
Ajax - In Rails
app/views/dogs/_form.html.erb <%= form_for(@dog) do |f| %> <% if @dog.errors.any? %>... <% end %> <% end %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> ... <div class="actions"> <%= f.submit %> </div><% end %>
Thursday, June 30, 2011
• Partials - Stay DRY
• Put partials into your code
• Render partial from controller
@Schneems
<h1>New dog</h1>
<%= render 'form' %>
<%= link_to 'Back', dogs_path %>
Ajax - In Rails
app/views/dogs/new.html.erb
def new @dog = Dog.new respond_to do |format| format.html # new.html.erb format.js {render :partial => "form"} format.xml { render :xml => @dog } endend
app/controllers/dogs.rb
Thursday, June 30, 2011
@Schneems
• Don’t go overboard
• Does it truly add to the functionality of the website?
• Does it take away anything from the website?
• What can we assume about the user?
• When in doubt, don’t use it
Ajax
Thursday, June 30, 2011
@Schneems
Questions?
http://guides.rubyonrails.orghttp://stackoverflow.com
Assignment for Next Week: Chapters 10, 11
Thursday, June 30, 2011