Title: Ruby on Rails
124
2- Convention is the ruler of all.
- Pindar
- Where the telescope ends, the microscope begins.
Which of the two has the grander view? - Victor Hugo
- We grow more partial for the observers sake.
- Alexander Pope
3- Those who cannot remember the past are condemned
to repeat it. - George Santayana
- Lets look at the record.
- Alfred Emanuel Smith
- All that matters is that the miraculousbecome
the norm. - Henry Miller
4OBJECTIVES
- In this chapter you will learn
- Basic Ruby programming.
- How to use the Rails framework.
- The Model-View-Controller paradigm.
- How to use ActiveRecord to model a database.
- How to construct web applications that
interactwith a database. - How to create a web-based message forum.
- How to develop Ajax-enabled applications in
Rubyon Rails. - How to use the built-in Script.aculo.us library
toadd visual effects to your programs.
5- 24.1 Introduction
- 24.2 Ruby
- 24.3 Rails Framework
- 24.4 ActionController and ActionView
- 24.5 A Database-Driven Web Application
- 24.6 Case Study Message Forum
- 24.6.1 Logging In and Logging Out
- 24.6.2 Embellishing the Models
- 24.6.3 Generating Scaffold Code
- 24.6.4 Forum Controller and Forum Views
- 24.6.5 Message Controller and Message Views
- 24.6.6 Ajax-Enabled Rails Applications
- 24.7 Script.aculo.us
- 24.8 Wrap-Up
- 24.9 Web Resources
624.1 Introduction
- Ruby on Rails (also known as RoR or just Rails)
is a framework for developing data-driven web
applications. - A web framework is a set of libraries and useful
tool that can be used to build dynamic web
applications. - Ruby on Rails is different from most other
programming languages because it takes advantage
of many conventions to reduce development time.
If you follow these conventions, the Rails
framework generates substantial functionality and
perform many tasks for you. - Ruby on Rails has built-in libraries for
performing common web development tasks, such as
interacting with a database, sending mass e-mails
to clients or generating web services. - Rails has built-in libraries that provide Ajax
functionality, improving the user experience.
Rails is quickly becoming a popular environment
for web development. - Ruby on Rails was created by David Heinemeier
Hansson of the company 37Signals.
724.2 Ruby
- The Ruby scripting language was developed by
Yukihiro Matz Matsumoto in 1995 to be a
flexible, object-oriented scripting language. - Rubys syntax and conventions are intuitivethey
attempt to mimic the way a developer thinks. Ruby
is an interpreted language. - Instant Rails is a stand-alone Rails development
and testing environment that includes Ruby,
Rails, MySQL, Apache, PHP and other components
necessary to create and run Rails applications. - If you are using Mac OS X, there is an
application similar to Instant Rails called
Locomotive. - The method puts prints the text to the terminal,
followed by a newline. - A method can have parentheses surrounding its
parameters, but this is not typical in Ruby
unless they are used to avoid ambiguity. - A line of Ruby code does not have to end with a
semicolon, although one can be placed there. - One way to run a Ruby script is to use the Ruby
interpreter. - IRB (Interactive Ruby) can be used to interpret
Ruby code statement by statement.
8Fig. 24.1 Instant Rails application running.
924.2 Ruby (Cont.)
- Ruby uses dynamic typing, which allows changes to
a variables type at execution time. - Everything is an object in Ruby, so you can call
methods on any piece of data. - Hash Objects are mapped to other Objects in
key/value pairs. - The exclamation point after a method name is a
Ruby convention indicating that the object on
which the method is called will be modified. - Ruby has support for code blocksgroupings of
Ruby statements that can be passed to a method as
an argument. - The initialize method acts like a constructor in
other object-oriented languagesit is used to
declare and initialize an objects data. - When each instance of a class maintains its own
copy of a variable, the variable is known as an
instance variable and is declared in Ruby using
the _at_ symbol. - Classes can also have class variables, declared
using the _at__at_ symbol, that are shared by all
copies of a class. - When an object is concatenated with a string, the
objects to_s method is called to convert the
object to its string representation.
10Outline
The puts command writes a line of text to the
console
welcome.rb
11Fig. 24.3 Launching the Ruby Interpreter in
Instant Rails.
12Fig. 24.4 Using the Ruby interpreter to run a
simple Ruby script.
13Fig. 24.5 Using Interactive Ruby to execute
Ruby statements.
14Outline
Ruby uses as the assignment operator
Enclosing a variable in curly braces ()preceded
by a pound sign () causes it to be interpolated
types.rb (1 of 2)
You can call the round method on any variable of
type Fixnum
Ruby variables are dynamically typed, so
variables have no explicit type, but can hold any
type of data at any time
15Outline
The capitalize method capitalizes the first
letter of a string
types.rb (2 of 2)
16Outline
Arrays can be created using comma-separated lists
in square brackets
arraysAndHashes.rb
The length of an array is stored in its length
property
Elements are accessed using square bracket
notation You can also access items starting from
the end of the array using negative indices
You can create a hash, which stores key-value
pairs, by separating keys from values with the gt
operator and enclosing the list in curly braces
17Outline
ControlStatements.rb
Methods are defined using the def keyword, and
method definitions end with the end keyword
The each method can be used on arrays to iterate
through their elements.
The parameters of a code block are placed between
pipe characters ()at the beginning of the block
18Outline
Classes are defined beginning with the class
keyword and ending with the end keyword
Classes.rb (1 of 2)
Class variables are preceded by _at__at_
Create a constructor by defining an initialize
method
Instance variables are preceded by _at_
Every class has a to_s method that returns a
string representation of the object. This class
overrides its to_s method
19Outline
Classes.rb (2 of 2)
Create an instance using the class name and new,
supplying any arguments required by the
constructor
2024.3 Rails Framework
- While users have benefitted from the rise of
database-driven web applications, web developers
have had to implement rich functionality with
technology that was not designed for this
purpose. - The Rails framework combines the simplicity of
development that has become associated with Ruby
with the ability to rapidly develop
database-driven web applications. - Ruby on Rails is built on the philosophy of
convention over configurationif you follow
certain programming idioms, your applications
will require little or no configuration and Rails
will generate substantial portions of the
applications for you. - The Model-View-Controller (MVC) architectural
pattern separates application data (contained in
the model) from graphical presentation components
(the view) and input-processing logic (the
controller). - ActiveRecord is used to map a database table to
an object. - ActionView is a set of helper methods to modify
user interfaces. - ActionController is a set of helper methods to
create controllers.
21Fig. 24.10 Model-View-Controller architecture.
22Fig. 24.11 Rails directory structure for a new
Rails application.
2324.4 ActionController and ActionView
- Ruby on Rails has two classes, ActionController
and ActionView, that work together to process a
client request and render a view. - To generate a controller in Rails, you can use
the built-in Controller generator by typing ruby
script/generate controller name. - A Ruby on Rails application must be run from a
web server - Instant Rails comes with a built-in web server
named Mongrel, which is easy to use to test Rails
applications on the local machine. - When generating output, a controller usually
renders a templatean XHTML document with
embedded Ruby that has the .rhtml filename
extension. - The request object contains the environment
variables and other information for a web page. - Erb (embedded Ruby) that is located between the
lt gt tags in rhtml files is parsed as Ruby code
and formatted as text. - A set of Ruby tags without an equals signlt
gtrepresents statements to execute as Ruby code
but not formatted as text. - Rails allows you to add headers and footers with
a layouta master view that is displayed by every
method in a controller. - A layout can generate a template for a specific
method using yield.
24Outline
app/controllers/welcome_controller.rb
Call the render method, specifying its parameter
using the text symbol
25Fig. 24.13 Starting the Mongrel web server.
26Outline
app/controllers/welcome_controller.rb
Define a class variable in the controller that
contains information about the server
27Outline
app/views/welcome/hello.rhtml
The view has access to the controllers class
variables
28Outline
app/views/layouts/welcome.rhtml
A controllers action_name method displays the
action that is currently being called
The layout yields to the view associated with the
current action
29Fig. 24.17 Creating a model in the Ruby
Console.
3024.5 A Database-Driven Web Application
- Rails makes extensive use of Object-Relational
Mapping (ORM) that maps a database to application
objects. - The objects that Rails uses to encapsulate a
database inherit from ActiveRecord. - One ActiveRecord convention is that every model
that extends ActiveRecordBase in an application
represents a table in a database. - By convention, the table that the model
represents has a name which is the lowercase,
pluralized form of the models name. - Rails uses a generator to create the Employee
model. You use a generator by typing ruby
script/generate model employee in the Ruby
Console, after navigating to your application
directory.
3124.5 A Database-Driven Web Application (Cont.)
- The ActiveRecord object has a special feature
called Migration, which allows you to perform
database operations within Rails. - ActiveRecord has built-in functionality for many
create, retrieve, update and destroy methods
known in Rails as CRUD. - We can execute the migration using Rubys rake
command by typing rake dbmigrate, which will
call the self.up method of all the migrations
located in your db/migrate directory. - If you ever want to roll back the migrations, you
can type rake dbmigrate VERSION0, which calls
each migrations self.down method. - The scaffold method is a powerful tool that
automatically creates CRUD functionality. It
creates methods such as new, edit and list so you
dont have to create them yourself.
32Outline
The up method in a migration does the work on the
database
db/migrate/001_create_employees.rb
We create a table in the database with three
columns containing strings
Create three entries in the table, specifying
values for each field
The down method undoes what the up method did so
that you can roll changes forward and back
To undo the changes, we simply drop the table
33Common Programming Error 24.1
- If the code that comes after the creation of the
table in the self.up is erroneous, the migration
will fail, and will not be able to execute again
because the table will already exist. Also, Rails
will not have marked the migration as
successfully completed, so the version will still
be 0 and the migration cannot be rolled back. One
way to prevent this problem is to force the table
to be dropped every time before creating it.
Another solution is splitting up the migration
into smaller discrete migrations, one to
createthe table and another to insert data in
the table.
34Outline
employee.rb
35Outline
The scaffold method dynamically generates any
CRUD methods that are not already defined in the
controller
app/controllers/employees_controller.rb
Our list method (called when the list action is
invoked) creates an array of all employees so
that the view can display them
36Fig. 24.21 View of the new action when
generated by the scaffold.
37Outline
app/views/employees/list.rhtml
Loop through each employee in the database
Access each employees first and last name as
properties of the current employee object
3824.6 Case Study Message Form
- Validators that will be called when the database
is modified, can be applied to an object that
inherits from ActiveRecord. - The method validates_presence_of ensures that all
the fields specified by its parameters are not
empty. - The method validates_format_of matches all the
fields specified by its parameters with a regular
expression. - The link_to method is used to link to an action
in the controller and pass arguments to it. - A partial is a block of HTML and embedded Ruby
code stored in another file and inserted directly
into the document. - Rails includes a JavaScript library called
Prototype that contains easy-to-use cross-browser
Ajax functions. - The javascript_include_tag helper method is used
to link in JavaScript libraries. - The link_to_remote method allows us to link to
JavaScript that we included in the layout file. - Specifying the url and update parameters inside
the link_to_remote method tells Rails to convert
these tags into prototype Ajax.Updater objects
that will update the page asynchronously.
39Outline
Create a database table to store users
db/migrate/001_create_users.rb
Create a test user
40Common Programming Error 24.2
- Creating a column without explicitly specifying a
limit on length will causeRails to truncate the
data entered intothe database with
database-defined limits.
41Outline
app/models/user.rb
42Outline
The admin action creates a new User
app/controllers/users_controller.rb
The validate action implements a login attempt
If the login is successful, store the User object
in a session variable
43Performance Tip 24.1
- Storing full objects in the session is
inefficient. The user object is one of the rare
exceptions, because it doesnt change very often
and is frequently needed in web applications that
manage the state information for unique clients.
44Outline
The login form submits to the validate action,
where the login information is processed
app/views/users/admin.rhtml
Both fields specify a model and a column to which
they correspond
45Outline
app/views/layouts/users.rhtml
46Outline
db/migrate/002_create_messages.rb
47Outline
Specify that each Message belongs to a Forum
app/models/message.rb
Validators make sure that a Message is not
created unless the title, author, email, and
message are defined, and the email is properly
formatted
48Outline
db/migrate/003_create_forums.rb
49Outline
app/models/forum.rb
A forum model is a container for multiple message
objects
When a forum is destroyed, all of its messages
are destroyed with it
50Outline
app/controllers/forums_controller.rb (1 of 2)
Ensure that anything modifying the database is
sent to the server as a POST request
Go back to the list page once a change has been
submitted
Use flash to display an error at the top of the
page if the user is not logged in
51Outline
app/controllers/forums_controller.rb (2 of 2)
Notify the user that their action was successful
Only allow the user to see a list of forums to
delete if the user is an administrator
Delete a forum and redirect to the list page
52Outline
Use the _at_forums array (defined in the controller)
to create a list of all
app/views/forums/list.rhtml (1 of 2)
53Outline
app/views/forums/list.rhtml (2 of 2)
54Outline
app/views/forums/new.rhtml
The render partial method inserts the contents
of a partial file (in this case _form.rhtml) into
a document
55Outline
app/views/forums/_form.rhtml
56Outline
app/views/forums/delete.rhtml
Use the collection_select method to generate a
drop-down menu from the _at_forms array.
57Outline
app/views/layouts/forums.rhtml (1 to 2)
58Outline
app/views/layouts/forums.rhtml (2 to 2)
Link to the admin action to allow the user to
login
59Outline
app/controllers/messages_controller.rb (1 to 2)
Get an array of messages belonging to the forum
with the forum_id stored in the session object
for the list action
60Outline
app/controllers/messages_controller.rb (2 to 2)
61Outline
app/views/messages/list.rhtml (1 to 2)
Format the creation time using the strftime
method of the Time object stored in
messagecreated_on
62Outline
app/views/messages/list.rhtml (2 to 2)
63Outline
app/views/messages/_form.rhtml (1 to 2)
The text_area method generates a textarea XHTML
element
64Outline
app/views/messages/_form.rhtml (2 to 2)
65Outline
app/views/layouts/messages.rhtml
The stylesheet_link_tag generates a link element
to an external style sheetin this case,
scaffold.cssin public/stylesheets/
66Outline
app/views/layouts/forums.rhtml (1 to 2)
Include the default JavaScript libraries,
including Script.aculo.us and Prototype
67Outline
app/views/layouts/forums.rhtml (2 to 2)
68Outline
app/views/forums/list.rhtml (1 to 2)
The link to each forum makes an Ajax call,
displaying the selected forums messages in the
currentForum div using a partial page update
Messages are displayed in this div
69Outline
app/views/forums/list.rhtml (2 to 2)
70Outline
app/views/messages/list.rhtml (1 to 2)
The New Message link puts the form in on the same
page using a partial page update
71Outline
app/views/messages/list.rhtml (2 to 2)
72Outline
Forum creation is also done without reloading the
entire page
app/views/messages/new.rhtml (1 to 2)
Canceling forum creation replaces the form with
the list of forums
73Outline
app/views/messages/new.rhtml (2 to 2)
7424.7 Script.aculo.us
- Script.aculo.us allows you to easily create
visual effects similar to those in Adobe Flash
and Microsoft Silverlight. - The library provides many pre-defined effects, as
well as the ability to create your own effects
from the pre-defined ones. - The Script.aculo.us library also provides
drag-and-drop capability through the
draggable_element and drop_receiving_element
methods. - The sortable_element method allows you to
describe a list that allows the user to drag and
drop list items to reorder them. - Script.aculo.us also provides the
text_field_with_auto_complete method, which
enables server-side autocompletion of a text
field.
75Fig. 24.46 Script.aculo.uss Fade effect.
76Outline
app/views/scriptaculous_demo/index.rhtml
Play a Shrink effect on the image div before
proceeding to the playEffect action
77Outline
app/controllers/scriptaculous_demo_controller.r
b
78Outline
app/views/layouts/application.rhtml
79Outline
app/views/scriptaculous_demo/_link.rhtml (1 to
5)
80Outline
app/views/scriptaculous_demo/_link.rhtml (2 to
5)
81Outline
app/views/scriptaculous_demo/_link.rhtml (3 to
5)
82Outline
app/views/scriptaculous_demo/_link.rhtml (4 to
5)
83Outline
app/views/scriptaculous_demo/_link.rhtml (5 to
5)
84Fig. 24.51 Flickr Photo Viewer showing search
results for bugs.
85Outline
app/view/flickr/index.rhtml (1 to 2)
A form that searches for tags, using blind
effects and a loading indicator
86Outline
app/view/flickr/index.rhtml (2 to 2)
87Outline
app/controllers/flickr_controller.rb
Search for tags and display paginated results
88Outline
app/views/flickr/_thumbs.rhtml
Display a thumbnail that links to the full sized
image
89Outline
app/views/flickr/fullsizeImage.rhtml
Display the full size version of an image