“X” Things, to Understand about Ruby on Rails

May 23, 2006 § Leave a comment

Understanding Ruby on
Rails:

“X” Things You Need To
Know

Ruby on
Rails
is perhaps the most innovative web
application framework since WebObjects ,
with developers claiming 10x boosts in productivity over J2EE. But, what is it
“really”? And why should I care? These notes and sample code complement the enormous number of
Ruby and Rails tutorials available elsewhere by exploring the key design
principles, patterns and techniques from the perspective of a long-time Cocoa
developer. The goal is to help you make an informed decision about why,
whether, and how to use Rails to accelerate your next web development
project.

“X”
Things

To Understand
About Ruby on Rails
0. How To Install
? Not my problem
? Lots of installers and tutorials already
available
? The big thing you really need to
understand: Ruby Gems
? At least use Rails
1.1.2

0a.
Examples

? Locomotive:
one-click rails on Mac OS X
? Rails Sandbox (via DarwinPorts) by James Duncan
Davidson
? Ruby
on Rails on Oracle: A Simple
Tutorial



1. What is
Rails?

“An opinionated toolset for
lightweight SQL-based web
apps”

a.
Opinionated

“Our way or the hard
way.”

? Convention over
Configuration
? Don’t Repeat Yourself
?
Pick one problem and solve it
well
? The Simplest Thing That Works
(TSTTW)
? Agile Development
? Get
Real(tm)

b.
Toolset

“Minimalist yet
complete.”

? Frameworks: ActiveRecord, ActionPack,
ActiveSupport, ActionMailer
? Commands: rails, rake,
script/*
? Templates: HTML, JavaScript
? Generators: models, controllers, views;
login, wiki, etc.
? Plug-Ins: web services, REST,
adaptors
? Testing: mock objects,
migrations
? Deployment: FastCGI,
Mongrel
? Plus, on Mac OS X: TextMate
(pseudo-IDE)

c.
Lightweight

? script-based
? fast-reloads
? shallow learning curve
? extremely terse
? lots of shortcuts and
time-savers
? minimal
configuration

d.
SQL-based

? Assumes SQL database
back-end
? Objects directly wrap tables, columns,
rows
? Easy to inject SQL if you
really
need to
? Can patch-in LDAP
et
al
, but not a great match
? Semi-awkward coexistence with Core
Data

e. Web
apps

? Built around HTTP request-response
? Optimized for HTML generation (plus
JavaScript)
? Partial support for SOAP web
services
? Emerging support for RESTful services
? Use of Mongrel as
a testing/proxy HTTP server

2.
Why NOT use Rails?

Might not be ideal if
you want:

? Reuse of existing legacy code and
datastores
? Model-driven development
(
mapping
versus
wrapping)
? Support from large IT consultancies and
corporations
? Complete enterprise-grade deployment
infrastructure (i.e., it is not WebObjects or J2EE)
? Sophisticated object caching
strategies
? Data from something other than an SQL
Database
? To vend something other than web
pages
? To avoid learning a new
language
? To really do things
your
way

3. Why
Ruby?

“Smalltalk with a friendly
syntax”

? Ruby : Objective-C :: Python : C ::
Perl : C++ (IMHO)
?
Everything
is an object (ints, classes, functions, methods, modules, etc.)
? Dynamically modify everything (unless
told not to; then just warn)
? More introspective than
Freud
? Clean yet flexible syntax (less spartan
than Python)
? Not just language, but culture and
worldview
? Rails = Ruby++ (naturally extend
fundamental constructs)
? Most scripters can just learn as they
go
? Remember: “ruby” for batch, “irb” for
interactive

3a.
Examples

? Try Ruby — 15 minute tutorial, run in your
browser
? Learning Ruby by Daniel Carrera
(2003)
? Ruby for Perl Programmers (October
2003)
? MacTech’s Introduction to Ruby for Mac OS X (March 2003)
? 10 Things Every Java Programmer Should Know
About Ruby (2005)
? Sam Ruby (no relation) on Ruby on Rails vs. Smalltalk
? More Learning Ruby Resources, from Max Kiesler (March
2006)
? Ruby vs. PHP discussion on SitePoint forums
(October 2005)
? Learn to
Program
, using Ruby (January 2006)
? Ruby the Galactic Gumshoe (1980’s radio program;
unrelated)

4.
Databases

“It’s the data,
stupid”

? The usual suspects: SQLite, MySQL,
Postgres, Oracle, etc.
? Flexible adaptors; easy to add more
(harder to natively optimize)
? Schema-driven
(
wrapping)
vs. model-driven
(
mapping)
? Just need to point to a database
(auto-create, at least
SQLite)

4a.
Example

? $ rails
xthings
# creates directory
infrastructure
? $ cd
!$
# do everything from within that
directory
? $ mate
config/database.yml
# point to that database
? development:?ÊÊ
adapter: sqlite3?ÊÊ dbfile:
db/xthings_development.db

5.
Generators & Migrations

“Code
generation done right”
(
enabling
human editing)

? $
script/generate model Thing
# model
class
? $ mate
app/models/thing.rb
# Look –
code!
? $ mate
db/migrate/001_create_things.rb
# How Ruby
manages databases
? t.column “name”,
:string
? t.column “state”, :string,
:default => “damned”
? $ rake
migrate
# runs
migration
to create “Thing” table with those columns
? $ sqlite3
db/xthings_development.db '.dump things'
#
Note plural
? $
script/generate scaffold

Thing #
controller + view templates
? $ mate
app/views/layouts/things.rhtml
# What, HTML +
Ruby in one file?
? $ mate
app/controllers/things_controller.rb
# Ah,
real code at last

6.
Deployment

“Web apps need a web
server”

?
WEBrick:
built-in, just works, pure Ruby; slooooow
?
FastCGI:
easy install, works with Apache or lighttpd
?
lighttpd:
optimized for FastCGI, will auto-detect and use
?
Apache:
works great; non-trivial configuration, awkward FastCGI
?
Mongrel:
“mostly Ruby”, fast but flexible, separate install (gem)
?
SCGI:
simpler FastCGI; overtaken by Mongrel + HTTP
proxy

6a.
Example

? $
script/server -d && open
http://localhost:3000
# -d =
“detach”
? $ mate
config/routes.rb
# show me my
Things!
? map.connect ”, :controller =>
“things”
? $ mv
public/index{,.old}.html
# hide default page
from webserver
? $ open
http://localhost:3000
# refresh default
route
? OR, interact directly via the
console
? $
script/console
? >> thing = Thing.new({:name =>
“#1”, :state => “Cursed”})
? >> thing.name
? >> thing.save
? >>
Thing.find_all

7. Active
Record

Object-Relational
Wrapping

? Each Table <=> One
Class
? Each Row <=> One
Object
? Each Column <=> One
Property
? Each update => One transaction (by
default)
? Lots of convenience methods
? Special method
generators
for 1-1, 1-many



7a.
Example
? $ script/generate model
Hat
# Create another table
? $ mate
db/migrate/002_create_hats.rb
# Add fields
linking “hats” to “things” ? t.column “thing_id”,
:integer
? t.column “color”, :string, :null
=> :false
? $ rake
migrate
? $ sqlite3 db/xthings_development.db
'.dump hats'
? $ mate
app/models/hat.rb
# edit model to capture
relationships in table
? belongs_to :thing # the table
containing a foreign key
? validates_associated
:thing
? validates_presence_of
“color”
? $ mate
app/models/thing.rb
? has_one :hat
? def before_destroy
?
Hat.find_by_thing_id(id).update_attribute(‘thing_id’,NIL)
? end
? $ script/console
? >> thing0 =
Thing.find_all[0]
? >> hat0 =
Hat.new({:color=>”Blue”, :thing_id=>thing.id})
? >> hat0.save
? >> hat0.thing.name
? >>
thing0.hat.color

8. Templates
and Controllers

“Make it easy to do
good, not hard to do wrong.”

? Templates versus tag
generation
? Embedded ruby: <% %>
? Use “h” to escape user-generated
text
? Generates human-readable
URLs
? Nearly 1-1 mapping between code and
output

8a. Example

?
$ script/generate scaffold Hat
?
$ mate
app/views/
things/edit.rhtml
?
<% if @thing.hat.nil? %>
?
<%= link_to "[New Hat]", :controller =>
"hats", :action => "new", :thing_id => @thing.id %>
?
<% else %>
?
<%=h @thing.hat.color %> hat
?
<%= link_to '[Edit Hat]', :controller =>
"hats", :action => "edit", :id => @thing.hat.id %>
?
<%= link_to '[Destroy Hat]', {:controller
=> "hats", :action => 'destroy', :id => @thing.hat.id }, :confirm =>
'Really destroy hat?', :post => true %>
?
<% end %>
?
$ mate
app/controllers/hats_controller.rb
?
def new
?
@hat = Hat.new
?
@hat.thing_id =
params[:thing_id]
?
end
?
redirect_to
:controller => ‘things’,
:action => ‘list’
?


9.
Testing

“Yes, there will be a test.”
? Actually, several.
? Generators automatically build test
harnesses
? -> Unit tests for model
objects
? -> Functional tests for Controller
objects
? Always run against a separate
database

9a.
Example

? $ mate
config/database.yml
# point to that database
? test:?ÊÊ adapter:
sqlite3?ÊÊ dbfile: db/xthings_test.db
? $ mate
tests/fixtures/hats.yml
# point to that
database
?
first:

? id:
1

? color:
“red”

?
another:

? id:
2

? color:
“green”
? $ rake
test

10.
Resources

“But wait, there’s
more!”

? Prototype (utilities) and Scriptaculous
(effects) JavaScript Libraries
? AJAX and RJS (JavaScript Templates)
? More graphs: Gruff,
Sparklines, CSS
Graphs
? Or even Camping
(“micro-Rails”)

10a.
Documentation

? Rails API reference
? Rails Cheat Sheet (png by Dave Child) or Cheat Sheat (PDF by Blaine Kendall)
? Ruby Cheat
Sheet
and QuickRef
? TextMate Cheat
Sheet
? -> TextMate for Rails Cheat Sheet, by Pragmatic
Studio
? -> TextMate for Rails Cheat Sheet, by
Feldpost

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

What’s this?

You are currently reading “X” Things, to Understand about Ruby on Rails at iHack, therefore iBlog.

meta

%d bloggers like this: