valuable cookbook will save you hundreds of hours when developing applications with Rails.... Rob's Rails Cookbook will hopefully do the same thing for those people just starting out wit
Trang 1By Rob Orsini
Publisher: O'Reilly Pub Date: January 01, 2007 ISBN-10: 0-596-52731-4 ISBN-13: 978-0-596-52731-0 Pages: 600
Table of Contents | Index
The Rails Cookbook is is packed with the solutions you need to be a proficient developer
with Rails, the leading framework for building the new generation of Web 2.0 applications Recipes range from the basics, like installing Rails and setting up your development
Trang 2valuable cookbook will save you hundreds of hours when developing applications with Rails.
Trang 3By Rob Orsini
Publisher: O'Reilly Pub Date: January 01, 2007 ISBN-10: 0-596-52731-4 ISBN-13: 978-0-596-52731-0 Pages: 600
Trang 10Copyright © 2007, O'Reilly Media All rights reserved
Printed in in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (http://safari.oreilly.com) For more information,contact our corporate/institutional sales department: (800)
While every precaution has been taken in the preparation of thisbook, the publisher and author assume no responsibility for
errors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 11When Rob asked me to write the foreword for his book I jumped
at the chance Actually, I jumped at telling him I'd write theforeword and then I got distracted with billions of things andhad to finally get it down in a flash of brilliance Trust me, it'sbrilliant This foreword will change your life, cure baldness, giveyour enemies lymphoma, and nuns will recite it to their classes
as a reward for good behavior It's that good
The reason I wanted to write a foreword for a cookbook, and
specifically for Rails Cookbook, is that I wouldn't be here today
if it weren't for this type of book When learning to write code,administer systems, or cook fish the young junior will typicallyrun out and get your basic introductory books These books trytake the newbie through a fixed road of learning that coversmost topics lightly in the curriculum At first this is great, andthe junior learns a lot of "bootstrap knowledge" with the things
he didn't know he didn't know getting filled in like grout overbroken tile
After this initial learning though, these books are fairly uselessbecause they are horrible references If you read them straightthrough and put stickies on the important pages you might getsomething out of it Having to troll through one of these densetomes to find that thing you thought you remembered in
chapter maybe 8 or 9 sucks really bad at 2 a.m Been there,done that, bought the pajamas in lime green
This is where the "cookbook" genre comes into play, and whythese types of books made me a better programmer The one
Trang 12Perl helped me take charge of a wildly managed heterogeneousnetwork of computers, and the cookbook helped me tame thewild Perl Perl was also my first light foray into CGI
programming and processing for the Web It was a great way tolearn CGI too, because all the nasty stuff was already takencare of, and Perl had all the gear you needed to program backthen Oh, I remember <blink> fondly
I'd have to say I didn't learn any Perl until I bought my copy ofthe cookbook, slammed it and a case of soda on a table, andspent an entire night writing a program to look for maliciousattacks in my system logs I'd read a few good books, but itwas the ability to ask a question, get an answer, then
implement the solution that taught me real Perl coding Best ofall, I could apply a technique, read about how it worked, andthen totally forget about it, only leaving a tiny marker in mybrain saying where to look it up again
With my Perl Cookbook I became a rock star geek in my own
little way My peers would spend hours trying to solve a
problem, and I'd just look it up and bang it out with Perl in afew minutes I could manage huge numbers of systems withsimple automation I even learned to appreciate some of thequirks of Perl for what they were
Why would I be talking about Perl in a Rails Cookbook
foreword? Well, apart from the fact that Rob said I could say
anything in the foreword, the Perl Cookbook was the one that
set the standard for me It doesn't matter what language it wasabout; what mattered was that this one book made me a
competent Perl programmer and system automator where
nearly all other books fell flat It's a great example of the
synergy of a set of components making the whole greater
The power of a good cookbook is its ability to impart expertknowledge in digestible chunks to beginners Just like with real
Trang 13practicing and doing expert activities and hopefully teaches
them the right way to do the tricks of the trade
Rob's Rails Cookbook will hopefully do the same thing for those
people just starting out with their first Ruby on Rails project Italso will be a good reference for those "beginning
intermediates" who still have to look things up they rarely use
or haven't done before It's also great for crusty old guys like
me who can't even remember what we had for breakfast thatmorning
Zed A Shaw, creator of Mongrel and MUDCRAP-CE Master Black Belt Sifu, (http://www.zedshaw.com)
Trang 14
I've been a full time web developer since 1998, and have
worked with just about every popular web scripting languageover the years During the dot-com boom, I kept busy in webconsulting shops, trying to turn various entrepreneurial ideasinto profitable web businesses The boom was a very interestingtime; the collective excitement over some of the first popularweb applications was infectious I wrote a lot of code duringthat time, some of which was a mess, but it was fun, and it was
an introduction to a career that I enjoy tremendously
When the dot-com bubble crashed, the tone of the industry
changed dramatically Web work dried up drastically, and theoverall enthusiasm of the industry seemed to sink into recessionalong with the industry's economy I managed to chain togethervarious web programming gigs, but the work was not as
interesting as it had been when people had more money to
experiment with new ideas
In 2004, I landed a job as the webmaster at Industrial Lightand Magic At ILM, I worked mostly with Perl and Java, but thiswas also where I was introduced to Python Toward the end of
my time at ILM, I began to hear about Ruby and a lot of thebuzz on the Net about it versus Pythonboth being very capableand lightweight dynamic languages While at ILM, I was
immersed in the excitement of the visual effects industry andmanaged to wait out the bad economy until finally landing asoftware engineering position at O'Reilly Media It was at
O'Reilly that I first found out about Rails
Around the time I started at O'Reilly, something very significanthappened: Google released Google Maps The economy hadbeen slowly recovering, but it was the release of this one webapplication that re-ignited my excitement about web
applications and their development What was so interesting
Trang 15technology It was just an incredibly creative use of
technologies that had been around for years
Being able to drag a map around seemed to shatter all previousassumptions about the limitations of web software After seeingthis application, and a number of others that were cropping up
at the time, my view of the potential of the Web, as well as myenthusiasm in developing it, was reborn Now, if I could justhave the same feeling about the tools I was using
That's when I discovered Rails and simultaneously, Ruby For
me, discovering and learning Rails had a similar effect to GoogleMaps; it seemed almost too good to be true Rails handled all ofthe things that I found most unpleasant about web
development automatically or so elegantly that they were nolonger painful The next thing I noticed was how easily new
projects were organized according to the MVC design pattern
I had worked on many MVC projects before, but often they
were home-grown and not easily reusable In some cases, theamount of setup involved made the benefits of using MVC
questionable, especially for smaller projects I've often said thatthe simple act of creating a Rails project felt like there was aroom full of experienced software veterans imparting their
knowledge about sound application design, ensuring that myproject started off in the right direction
I soon realized that nothing about the Rails framework or thebest practices encouraged by the Rails community was
particularly new In fact, most of the techniques and
methodologies involved have been around for years What Ifound special about Rails was that all of these things had cometogether, in sort of a perfect storm of best practices The resultwas a framework that made web development both enjoyableand rewarding
With a number of Rails projects behind me, I started doing talks
Trang 16Who This Book Is For
In preparation for writing this book, I tried to collect a lot ofdata about what the Rails community needed most in a
cookbook To do this I collected data from the Rails mailing lists
as well as from the most active IRC channels I wasn't very
scientific about how I processed the data, but I did get a feel forwhat were many of the most commonly asked questions Based
on this, I created an initial outline, and then ran it past as manypeople as I could find, who reviewed and further edited it
The outline has evolved since I first presented it to my editor,but it still targets the needs of the bulk of the Rails community.The target reader for this book is someone with web
development experience, but perhaps new to Rails, or an
intermediate Rails developer
That said, I believe that much of the information I present isgoing to be valuable across the board; for example, Rails
application deployment is a universal problem that all Rails
developers need to solve In the end, I hope that everyone whoreads this book will find it significantly useful
Trang 17Hibbs (O'Reilly)
Trang 18Some code samples have filenames mentioned before the code;the files that accompany the code can be found on the book'sweb page at http://www.oreilly.com/catalog/9780596527310
Font Conventions
The following typographic conventions are used in this book:
Italic
Used for file and directory names, email addresses, andURLs, as well as for new terms where they are defined
Constant width
Used for code listings and for keywords, variables,
functions, command options, database names, parameters,class names, and HTML tags where they appear in the text
Trang 19bold
Used to mark lines of output in code listings and commandlines to be typed by the user
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books doesrequire permission Answering a question by citing this book
Trang 20Incorporating a significant amount of example code from thisbook into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Rails Cookbook by Rob Orsini Copyright 2007
O'Reilly Media, Inc., 978-0-596-52731-0."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
Comments and Questions
Trang 21http://www.oreilly.com/catalog/9780596527310
To comment or ask technical questions about this book, sendemail to:
The book's biggest contributor, aside from myself, has been
Mike Loukides Mike's input was invaluable, whether he was
refactoring a confusing paragraph or offering an insight about
an idea I hadn't thought to include, he was there helping everystep of the way The great thing about working with Mike is that
Trang 22conversation being a side-track of something else
Fifteen people contributed recipes to the book I'd like to pointout the three that helped me the most during the final stages ofthe process Diego Scataglini contributed the most recipes (12total) More importantly, he produced many of these recipeswith very short notice as I pushed to fit in more content beforethe final deadline Christian Romney and Ryan Waldron alsostepped up to the plate in the final stages and helped fill outand clean up much of the book's content During the final days,the three of us collaborated in #rorcb (a.k.a The War Room),where I was able to delegate a huge amount of work to each ofthem Their contribution was outstanding but, most importantly,
we had a great time in the process I'm grateful to everyonewho contributed recipes They include Ben Bleything, BlaineCook, Ryan Daigle, Bill Froelich, Evan Henshaw-Plath, Rick
Olson, Matt Ridenour, Dae San Hwang, Andy Shen, Joe Van
Dyk, Nicholas Wieland, and Chris Wong
More special thanks goes to Coda Hale for doing an excellentpass over the book resulting in several emails full of valuablesuggestions Also thanks to Evan Henshaw-Plath (rabble), ZedShaw, and Geoffrey Grosenbach (topfunky) for putting up withmany late night Rails questions and offering sound advice alongthe way
The tool that I settled on for collaborating with reviewers wasBeast (an excellent Rails forum written by Josh Goebel and RickOlson) A number of discussions happened there that definitelyimproved the book several times over I'm thankful to all whoreviewed my content and posted comments They include SamAaron, Anjan Bacchu, Tony Frey, Matt Grayson, Stephan
Kamper, Bin Li, Tom Lianza, Thomas Lockney, Matt McKnight,James Moore, Hartmut Prochaska, Andy Shen, Bill Spornitz,
Trang 23During the initial months of writing I switched between severaldifferent writing environments I finally settled on editing
directly in DocBook Once I accumulated a certain amount ofcontent and needed to perform various transformations, I
quickly discovered the limits of my knowledge of XML
processing This is where Keith Fahlgren and Andrew Savikasstepped in with just the right XPath expression or XMLMind
macro to get the job done, which let me focus on writing
Writing a book is like nothing I've ever done before Because ofthat, I'm thankful that I was able to talk with my friends whohave written books about the process Those friends are KyleRankin, Andrew Savikas, and Tony Stubblebine
Finally, I want to thank my wife for helping make this projectpossible She essentially became a single parent for quite a bitlonger then she bargained for I am grateful for her support andencouragement
Trang 24
Recipe 1.8 Running Rails in Windows with Instant RailsRecipe 1.9 Updating Rails with RubyGems
Recipe 1.10 Getting Your Rails Project into Subversion
Trang 25Since it first appeared in July 2004, Ruby on Rails has
revolutionized the process of developing web applications Ithas enabled web developers to become much faster and moreefficient, allowing for quicker application developmenta criticaladvantage in these days of "web time." How does Rails do it?There are a few reasons behind Rails' success:
Convention over configuration
Rather than forcing you to configure every aspect of yourapplication, Rails is full of conventions If you can followthose conventions, you can do away with almost all
configuration files and a lot of extra coding If you can'tfollow those conventions, you're usually no worse off thanyou were in your previous environment
Liberal use of code generation
Rails can write a lot of your code for you For example,
when you need a class to represent a table in your
database, you don't have to write most of the methods:Rails looks at the table's definition and creates most of theclass for you on the fly You can mix in many extensions toadd special behavior, and when you really need to, you canadd your own methods You'll find that you're writing only afraction as much code as you did with other web
frameworks
Don't repeat yourself (DRY)
Trang 26to code behavior only once; you never (well, almost never)have to write similar code in two different places Why isthis important? Not because you type less, but becauseyou're less likely to make mistakes by modifying one chunk
of code, and not another
David Heinemeier Hansson and the other Ruby on Rails coredevelopers have learned from the mistakes of other web
application frameworks and taken a huge step forward Ratherthan provide an extremely complex platform that can solveevery problem out of the box if you can only understand it,Rails solves a very simple problem extremely well With thatsolution under your belt, you'll find that it's a lot easier to work
up to the hard problems It's often easier, in fact, to solve thehard problem for yourself with Rails than to understand someother platform's solution Want to find out whether Rails is
everything it's cracked up to be? Don't wait; try it If you're not
a Ruby developer yet, don't worry; you only need to know alimited amount of Ruby to use Rails I'd be willing to bet thatyou'll want to learn more, though
Trang 27Problem
You know that Rails is an evolving open source project, and youwant to stay on top of the latest developments Where do youget your questions answered, and how do you know what newfeatures are being developed?
Solution
Like most popular open source projects, Rails has a number ofmailing lists that developers, system administrators, and otherinterested parties can join to stay abreast of the latest
developments These lists also have searchable archives thatwill help you understand the evolution of a feature Currently,the following mailing lists are available:
Trang 28(http://colloquy.info), or for terminal fans, Irssi
(http://www.irssi.org)
One great place to ask questions and look for answers is RailsWeenie (http://rails.techno-weenie.net) This site uses a points-based system in an attempt to persuade people to answer morequestions, and to ask more sensible questions When you create
an account, you automatically receive five points You can offerthese points as a reward for questions you want answered Ifsomeone answers the question, they get the number of pointsyou offered Also, if you answer other people's questions, youget the number of points they offered It's not as responsive asIRC, but you're far more likely to get a more thorough answer
to your question
The Rails Forum (http://railsforum.com) is another active
community of Rails users, with members of all levels of Railsexperience
Trang 29(RUGs) in your area (
http://www.ruby-lang.org/en/community/user-groups) If there isn't a local Railsgroup where you live, perhaps you can start one!
Lastly, a large part of the Rails community exists in the
blogosphere, where participants post anything from tutorials toexplorations of the latest new features of the framework as
they're being developed Two popular blogs that aggregate
individual Ruby and Rails blogs are http://www.rubycorner.comand http://www.planetrubyonrails.org
Discussion
The Rails community is relatively young, but strong and growingfast If you've got questions, there are plenty of people willing
to help you answer them They'll help you get the hang of Railsdevelopment, and you can return the favor by helping others oreven contributing to the project
The Rails mailing list has lots of traffic: currently about 400
messages per day This means that you can post a question andsoon have it buried under a screen full of newer messages Thetrick to coping with this information overload is to use very
clear and descriptive subject lines and problem descriptions
The #rubyonrails IRC channel is also very busy, but it is a greatresource for instant feedback Just make sure you respect
simultaneous conversations Rather than pasting code examplesinto the channel, post them to an external site (e.g.,
http://pastie.caboo.se) In fact, when you're in the IRC channelsimply say, "Hi pastie," and the pastie bot will send you a link towhere you can post your code
Trang 30Section 1.2"
Trang 31Problem
You're beginning to develope Rails applications, and you havequestions You need to find the latest documentation for Ruby,Rails, and RubyGems libraries
Solution
The documentation for the latest stable version of the Rails API
is online at http://api.rubyonrails.com A group of hardcoreRails developers also maintains documentation on the bleeding-edge version of Rails at http://caboo.se/doc The latest Rubydocumentation is always available at http://www.ruby-doc.org.Here you can find documentation on the Ruby Core library, theRuby Standard Library, and the C API In regards to third-partylibraries, a comprehensive set of RubyGems documentation isavailable at http://www.gemjack.com You can also view
documentation on any RubyGems you have installed on yourlocal system by starting the gem server with the following
you'll find a vast amount of user contributed content While
Trang 32of it can be out of date or inaccurate
Of late, there's been a growing trend to consolidate essential
documentation into so-called cheatsheets A quick web searchfor Ruby, Rails, or Prototype cheatsheets should yield some
Last but not least, GotApi (http://www.gotapi.com) might best
be described as a documentation aggregator It's a very usefulsite for looking up not only Ruby and Rails documentation, butother related docs (like JavaScript and CSS)
Discussion
The API documentation can be a little awkward The format is
best suited for looking up the methods of a class or the options
of a specific method, and less helpful as an introduction to theframework One way to become familiar with the major
components of Rails via the API is to read the documentation
for each base class (e.g., ActionController::Base, ActiveRecord::Base)
As you become more proficient with Ruby and Rails, you'll
definitely want to browse the source code itself This experiencecan be a little overwhelming if you're new to the language or
the framework, but there's truly no substitute if you want to
understand how all the magic works behind the scenes
Mauricio Fernandez, a long-time Rubyist, keeps a self-study
guide to the Ruby source code on his web site
Trang 34Problem
You want to install a MySQL relational database server to beused by your Rails applications
Solution
Windows
win32.zip from http://dev.mysql.com/downloads Depending onwhich version of MySQL you download, you should see either a
If you're a Windows user, download and unzip mysql-5.0.18-setup.exe file or a msi file Click on one of these to start the
installation wizard For most cases, you can select the standardconfiguration, which includes the mysql command-line client andseveral other administration utilities, such as mysqldump
By default, the installation wizard sets up MySQL as a servicethat starts automatically Another option is to have the installerinclude MySQL's binary directory in the Windows PATH, allowingyou to call the MySQL utilities from the Windows command line.Once the installation is complete, you can start up mysql as theroot user at the command prompt as shown in Figure 1-1
Figure 1-1 Interaction with MySQL from the
command prompt
Trang 35Linux
Trang 39highest numbered version of the gem that ends with (ruby)
Discussion
The recommended way to install MySQL on Linux is to use yourdistribution's package management system On a Debian
GNU/Linux system, package management is handled by dpkg,which is similar to the RPM system used by Red Hat
distributions The easiest way to administer dpkg is with the aptsuite of tools, which includes apt-cache and apt-get
Once you've got the MySQL server installed, you need to createone or more databases and users While it's convenient to
create a database from a script, to make it easy to recreatethere are also a number of GUI tools for setting up and
administering MySQL databases Get the official MySQL GUItools from http://dev.mysql.com/downloads Even if you create
Trang 40command-line user interface) is included; if you prefer a GUIadministration tool, also include pgAdmin III.