- •Contents
- •Preface to the Second Edition
- •Introduction
- •Rails Is Agile
- •Finding Your Way Around
- •Acknowledgments
- •Getting Started
- •Active Record: Rails Model Support
- •The Architecture of Rails Applications
- •Models, Views, and Controllers
- •Action Pack: The View and Controller
- •Installing Rails
- •Your Shopping List
- •Installing on Windows
- •Installing on Mac OS X
- •Installing on Linux
- •Development Environments
- •Rails and Databases
- •Rails and ISPs
- •Creating a New Application
- •Hello, Rails!
- •Linking Pages Together
- •What We Just Did
- •Building an Application
- •The Depot Application
- •Incremental Development
- •What Depot Does
- •Task A: Product Maintenance
- •Iteration A1: Get Something Running
- •Iteration A2: Add a Missing Column
- •Iteration A3: Validate!
- •Iteration A4: Prettier Listings
- •Task B: Catalog Display
- •Iteration B1: Create the Catalog Listing
- •Iteration B4: Linking to the Cart
- •Task C: Cart Creation
- •Sessions
- •Iteration C1: Creating a Cart
- •Iteration C2: A Smarter Cart
- •Iteration C3: Handling Errors
- •Iteration C4: Finishing the Cart
- •Task D: Add a Dash of AJAX
- •Iteration D1: Moving the Cart
- •Iteration D3: Highlighting Changes
- •Iteration D4: Hide an Empty Cart
- •Iteration D5: Degrading If Javascript Is Disabled
- •What We Just Did
- •Task E: Check Out!
- •Iteration E1: Capturing an Order
- •Task F: Administration
- •Iteration F1: Adding Users
- •Iteration F2: Logging In
- •Iteration F3: Limiting Access
- •Iteration F4: A Sidebar, More Administration
- •Task G: One Last Wafer-Thin Change
- •Generating the XML Feed
- •Finishing Up
- •Task T: Testing
- •Tests Baked Right In
- •Unit Testing of Models
- •Functional Testing of Controllers
- •Integration Testing of Applications
- •Performance Testing
- •Using Mock Objects
- •The Rails Framework
- •Rails in Depth
- •Directory Structure
- •Naming Conventions
- •Logging in Rails
- •Debugging Hints
- •Active Support
- •Generally Available Extensions
- •Enumerations and Arrays
- •String Extensions
- •Extensions to Numbers
- •Time and Date Extensions
- •An Extension to Ruby Symbols
- •with_options
- •Unicode Support
- •Migrations
- •Creating and Running Migrations
- •Anatomy of a Migration
- •Managing Tables
- •Data Migrations
- •Advanced Migrations
- •When Migrations Go Bad
- •Schema Manipulation Outside Migrations
- •Managing Migrations
- •Tables and Classes
- •Columns and Attributes
- •Primary Keys and IDs
- •Connecting to the Database
- •Aggregation and Structured Data
- •Miscellany
- •Creating Foreign Keys
- •Specifying Relationships in Models
- •belongs_to and has_xxx Declarations
- •Joining to Multiple Tables
- •Acts As
- •When Things Get Saved
- •Preloading Child Rows
- •Counters
- •Validation
- •Callbacks
- •Advanced Attributes
- •Transactions
- •Action Controller: Routing and URLs
- •The Basics
- •Routing Requests
- •Action Controller and Rails
- •Action Methods
- •Cookies and Sessions
- •Caching, Part One
- •The Problem with GET Requests
- •Action View
- •Templates
- •Using Helpers
- •How Forms Work
- •Forms That Wrap Model Objects
- •Custom Form Builders
- •Working with Nonmodel Fields
- •Uploading Files to Rails Applications
- •Layouts and Components
- •Caching, Part Two
- •Adding New Templating Systems
- •Prototype
- •Script.aculo.us
- •RJS Templates
- •Conclusion
- •Action Mailer
- •Web Services on Rails
- •Dispatching Modes
- •Using Alternate Dispatching
- •Method Invocation Interception
- •Testing Web Services
- •Protocol Clients
- •Secure and Deploy Your Application
- •Securing Your Rails Application
- •SQL Injection
- •Creating Records Directly from Form Parameters
- •Avoid Session Fixation Attacks
- •File Uploads
- •Use SSL to Transmit Sensitive Information
- •Knowing That It Works
- •Deployment and Production
- •Starting Early
- •How a Production Server Works
- •Repeatable Deployments with Capistrano
- •Setting Up a Deployment Environment
- •Checking Up on a Deployed Application
- •Production Application Chores
- •Moving On to Launch and Beyond
- •Appendices
- •Introduction to Ruby
- •Classes
- •Source Code
- •Resources
- •Index
- •Symbols
INSTALLING ON LINUX |
35 |
The first comes from Dan Benjamin. His article, Building Ruby, Rails, LightTPD, and MySQL on Tiger, is a step-by-step guide to downloading and building all the software you need to turn your Mac into a Rails machine. Find it at
• http://hivelogic.com/articles/2005/12/01/ruby_rails_lighttpd_mysql_tiger
An alternative approach is to let the computer do some of the low-level work for you. There are at least two package management systems for OS X. These handle downloading, dependency management, installation, and updating of software. James Duncan Davidson has a great description of how to use the MacPorts package management system to install Rails on OS X. (When Duncan wrote this article, MacPorts was still called DarwinPorts.) Duncan’s approach has one real advantage: because the package manager handles dependencies, it makes it easier to upgrade and roll back versions of the individual components. It has one slight disadvantage: you delegate control of your installation layout to the package manager, so you do things the MacPorts way or not at all. In practice, this isn’t a problem. Anyway, you’ll find Duncan’s write-up at
• http://duncandavidson.com/essay/2006/04/portsandbox
Read both through, make your choice, and then go for it. We’ll wait.... When you come back, join us on the following page for a discussion of editors.
Locomotive Mac Installation
You can download Locomotive as a .dmg file from http://locomotive.raaum.org. Mount it, and drag the Locomotive folder somewhere appropriate. Then start Locomotive by navigating into the folder and running Locomotive.app (but only after admiring the cool train icon).
Locomotive lets you import existing Rails projects and create new projects. Its main window displays a list of all the Rails projects that it is managing and allows you to start and stop those applications. You edit your application’s files outside Locomotive.
If you decided to peek at the Windows installation instructions, you’ll have seen that there’s a strong warning: use the console supplied by InstantRails to type Rails commands. Well, the same is true here. When using Locomotive, you must use its console to type commands. Access it from the Applications → Open Terminal menu option.
3.4Installing on Linux
If you are the “I-code-by-twiddling-the-bits-on-my-hard-drive-with-a-magnet” kind of Linux user, then Dan Benjamin’s instructions for the Mac will probably get you going. One caveat: be wary if your box already has Ruby installed: it may not have the libraries you need. I (Dave) always install Ruby into a
Report erratum
DEVELOPMENT ENVIRONMENTS |
36 |
directory under my home directory (say ~/ruby) and then include ~/ruby/bin in my path.
The rest of us mortals will probably use our distribution’s package manager to install the code we need (pretty much the way James Duncan Davidson’s instructions did for the Mac). But, because each distribution is different, we’re going to punt on the details and instead reference an online resource that has the scoop for Ubuntu, the popular Debian-based distribution. The link here is for the “Dapper Drake” distribution. You may find that this has been superceded by the time you read this.
•http://wiki.rubyonrails.com/rails/pages/RailsOnUbuntuDebianTestingAndUnstable
•http://wiki.rubyonrails.com/rails/pages/RailsOnUbuntu
3.5Development Environments
The day-to-day business of writing Rails programs is pretty straightforward. Everyone works differently; here’s how I work.
The Command Line
I do a lot of my work at the command line. Although there are an increasing number of GUI tools that help generate and manage a Rails application, I find the command line is still the most powerful place to be. It’s worth spending a little while getting familiar with the command line on your operating system. Find out how to use it to edit commands that you’re typing, how to search for and edit previous commands, and how to complete the names of files and commands as you type.5
Version Control
I keep all my work in a version control system (currently Subversion). I make a point of checking a new Rails project into Subversion when I create it and commiting changes once I’ve got passing tests. I normally commit to the repository many times an hour.
If you’re working on a Rails project with other people, consider setting up a continuous integration (CI) system. When anyone checks in changes, the CI system will check out a fresh copy of the application and run all the tests. It’s simple insurance against you accidentally breaking stuff when you make a change. You also set up your CI system so that your customers can use it
5. So-called tab completion is standard on Unix shells such as Bash and zsh. It allows you to type the first few characters of a filename, hit Tab , and have the shell look for and complete the name based on matching files. This behavior is also available by default in the Windows XP command shell. You can enable this behavior in older versions of Windows using the freely available TweakUI power toy from Microsoft.
Report erratum
DEVELOPMENT ENVIRONMENTS |
37 |
Where’s My IDE?
If you’re coming to Ruby and Rails from languages such as C# and Java, you may be wondering about IDEs. After all, we all know that it’s impossible to code modern applications without at least 100MB of IDE supporting our every keystroke. For you enlightened ones, here’s the point in the book where we recommend you sit down, ideally propped up on each side by a pile of framework references and 1,000 page “Made Easy” books.
There are no fully fledged IDEs for Ruby or Rails (although some environments come close). Instead, most Rails developers use plain old editors. And it turns out that this isn’t as much of a problem as you might think. With other, less expressive languages, programmers rely on IDEs to do much of the grunt work for them: IDEs do code generation, assist with navigation, and compile incrementally to give early warning of errors.
With Ruby, however, much of this support just isn’t necessary. Editors such as TextMate give you 90% of what you’d get from an IDE but are far lighter weight. Just about the only useful IDE facility that’s missing is refactoring support.
. I prefer using one editor for everything. Others use specialized editors for creating application code versus (say) HTML layouts. For the latter, look for plugins for popular tools such as Dreamweaver.
to play with the bleeding-edge version of your application. This kind of transparency is a great way of ensuring that your project isn’t going off the tracks.
Editors
I write my Rails programs using a programmer’s editor. I’ve found over the years that different editors work best with different languages and environments. For example, I’m writing this chapter using Emacs, as its Filladapt mode is unsurpassed when it comes to neatly formatting XML as I type. But Emacs isn’t ideal for Rails development: I use TextMate for that. Although the choice of editor is a personal one, here are some suggestions of features to look for in a Rails editor.
•Support for syntax highlighting of Ruby and HTML. Ideally support for
.rhtml files (a Rails file format that embeds Ruby snippets within HTML).
•Support of automatic indentation and reindentation of Ruby source. This is more than an aesthetic feature: having an editor indent your program as you type is the best way of spotting bad nesting in your code. Being able to reindent is important when you refactor your code and move stuff. (TextMate’s ability to reindent when it pastes code from the clipboard is very convenient.)
Report erratum
DEVELOPMENT ENVIRONMENTS |
38 |
•Support for insertion of common Ruby and Rails constructs. You’ll be writing lots of short methods: if the IDE creates method skeletons with a keystroke or two, you can concentrate on the interesting stuff inside.
•Good file navigation. As we’ll see, Rails applications are spread across many files.6 You need an environment that helps you navigate quickly between these: you’ll add a line to a controller to load up a value, switch to the view to add a line to display it, and then switch to the test to verify you did it all right. Something like Notepad, where you traverse a File Open dialog to select each file to edit, just won’t cut it. I personally prefer a combination of a tree view of files in a sidebar, a small set of keystrokes that’ll let me find a file (or files) in a directory tree by name, and some built-in smarts that knows how to navigate (say) between a controller action and the corresponding view.
•Name completion. Names in Rails tend to be long. A nice editor will let you type the first few characters and then suggest possible completions to you at the touch of a key.
We hesitate to recommend specific editors because we’ve used only a few in earnest and we’ll undoubtedly leave someone’s favorite editor off the list. Nevertheless, to help you get started with something other than Notepad, here are some suggestions.
•TextMate (http://macromates.com/): The Ruby/Rails editor of choice on Mac OS X.
•RadRails (http://www.radrails.org/): An integrated Rails development environment built on the Eclipse platform that runs on Windows, Mac OS X, and Linux. (It won an award for being the best open source developer tool based on Eclipse in 2006.)
•jEdit (http://www.jedit.org/): A fully featured editor with support for Ruby. It has extensive plugin support.
•Komodo (http://www.activestate.com/Products/Komodo/): ActiveState’s IDE for dynamic languages, including Ruby.
•Arachno Ruby (http://www.ruby-ide.com/ruby/ruby_ide_and_ruby_editor.php): A commercial IDE for Ruby.
Ask experienced developers who use your kind of operating system which editor they use. Spend a week or so trying alternatives before settling in. And, once you’ve chosen an editor, make it a point of pride to learn some new feature every day.
6. A newly created Rails application enters the world containing 44 files spread across 36 directo-
ries. That’s before you’ve written a thing....
Report erratum
