Beginning Ruby on Rails.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
01_069155 ffirs.qxp 10/23/06 8:02 PM Page i Beginning Ruby on Rails™ 01_069155 ffirs.qxp 10/23/06 8:02 PM Page ii 01_069155 ffirs.qxp 10/23/06 8:02 PM Page iii Beginning Ruby on Rails™ Steven Holzner 01_069155 ffirs.qxp 10/23/06 8:02 PM Page iv Beginning Ruby on Rails™ Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN-13: 978-0-470-06915-8 ISBN-10: 0-470-06915-5 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/QZ/RR/QW/IN Library of Congress Catalog Control Number: 2006030329 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen- ter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indi- anapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE- FROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAP- PEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Ruby on Rails is a trademark of David Heinemeier Hansson. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. 01_069155 ffirs.qxp 10/23/06 8:02 PM Page v To Nancy, now and always! 01_069155 ffirs.qxp 10/23/06 8:02 PM Page vi 01_069155 ffirs.qxp 10/23/06 8:02 PM Page vii About the Author Steven Holzner is the award-winning author of more than 100 programming books. He’s been involved in Ruby on Rails for a long time, and does commercial Rails development. He’s also been on the faculty of Cornell University and MIT, as well as having been a contributing editor for PC Magazine. 01_069155 ffirs.qxp 10/23/06 8:02 PM Page viii 01_069155 ffirs.qxp 10/23/06 8:02 PM Page ix Credits Acquisitions Editor Vice President and Executive Publisher Kit Kemper Joseph B. Wikert Development Editor Project Coordinators Maryann Steinhart Heather Kolter, Ryan Steffen Technical Editor Graphics and Production Specialists David Mabelle Carrie A. Foster Denny Hager Production Editor Barbara Moore Angela Smith Lynsey Osborn Laura Pence Copy Editor Alicia B. South Kim Cofer Quality Control Technicians Editorial Manager John Greenough Mary Beth Wakefield Brian H. Walls Production Manager Tim Tate Proofreading and Indexing Techbooks Vice President and Executive Group Publisher Richard Swadley 01_069155 ffirs.qxp 10/23/06 8:02 PM Page x 01_069155 ffirs.qxp 10/23/06 8:02 PM Page xi Acknowledgments The book you hold in your hands is the work of many people. I’d especially like to thank Kit Kemper, Maryann Steinhart, and all of the other Wiley editors who worked on this project for their contribution to its success. 01_069155 ffirs.qxp 10/23/06 8:02 PM Page xii 02_069155 ftoc.qxp 10/23/06 8:02 PM Page xiii Contents Acknowledgments xi Introduction xix Chapter 1: Welcome to Ruby 1 Installing Ruby and Rails 1 Install Ruby and Rails on Windows 1 Install Ruby and Rails in Mac OS X 2 Install Ruby and Rails in Linux and Unix 2 Database System 3 Creating a First Web Application 3 Getting Started with Ruby 7 Checking the Ruby Documentation 9 Working with Numbers in Ruby 10 Working with Strings in Ruby 11 Storing Data in Variables 13 Creating Constants 15 Interpolating Variables in Double-Quoted Strings 15 Reading Text on the Command Line 16 Creating Symbols in Ruby 18 Working with Operators 18 Handling Operator Precedence 21 Working with Arrays 21 Using Two Array Indices 24 Working with Hashes 27 Working with Ranges 29 Summary 31 Exercises 32 Chapter 2: Conditionals, Loops, Methods, and Blocks 33 It’s All about Making Choices: the if Statement 33 Using else Clauses in if Statements 34 Using elsif Clauses in if Statements 35 Using the unless Statement 37 Using if and unless as Modifiers 38 02_069155 ftoc.qxp 10/23/06 8:02 PM Page xiv Contents Using the case Statement 39 Using Loops 41 Using the while Loop 42 Using the until Loop 42 Using while and until as Modifiers 43 Using the for Loop 44 Using the Ruby Iterators 45 Working with break, redo, and next in Loops 48 Using the retry Statement 50 Creating and Calling a Method 51 Passing Arguments to a Method 52 Passing a Variable Number of Arguments 53 Returning a Value from a Method 54 Returning Multiples Values from a Method 56 Making Use of Scope 57 Working with Blocks 58 Passing Data to Blocks 60 Using BEGIN and END Blocks 61 Summary 61 Exercises 62 Chapter 3: Classes and Objects 63 All about Encapsulation 63 Creating a Class 64 Creating an Object 66 Using a Constructor to Configure Objects 67 Understanding Ruby Attributes 68 Creating Readable Attributes 68 Creating Writable Attributes 69 Creating Readable and Writable Attributes 71 Basing One Class on Another 72 Understanding Ruby’s Object Access 75 Using Protected Access 76 Using Private Access 78 Overriding Methods 79 Creating Class Variables 80 Creating Class Methods 82 Creating Modules 83 Creating Mixins 85 Summary 87 Exercises 87 xiv 02_069155 ftoc.qxp 10/23/06 8:02 PM Page xv Contents Chapter 4: Welcome to Rails 89 Putting Ruby on Rails 89 Creating the Application Framework 90 Running the Application 93 Creating the Controller 94 Using the Rails Documentation 94 Testing the Controller 95 Creating an Action 96 Creating a View 97 Introducing Model-View-Controller Architecture 100 The Controller 101 The View 101 The Model 102 Giving the View Something to Do 102 Mixing Ruby Code and HTML Inside the View 105 Passing Data from an Action to a View 108 Escaping Sensitive Text 111 Adding a Second Action 113 Selecting Which View to Render 116 Rendering Any Template 118 Linking to Another Action 118 Summary 120 Exercises 121 Chapter 5: Building Simple Rails Applications 123 Accessing Data the User Provides 123 Reading Data from Text Fields 123 Reading Data from Checkboxes 127 Reading Data from Radio Buttons 130 Reading Data from Select Controls 132 Using Rails Shortcuts for HTML Controls 137 Working with Models 143 Tying Controls to Models 145 Initializing Data in Controls 151 Storing Data in Sessions 153 Summary 157 Exercises 157 xv 02_069155 ftoc.qxp 10/23/06 8:02 PM Page xvi Contents Chapter 6: Connecting to Databases 159 Tutorial on Databases 159 Creating a Data-Aware Rails Application 162 Creating the Database 162 Configuring Database Access 165 Creating the Controller and Model 167 Naming the Model 168 Naming the Controller 168 Running the store Application 169 Adding a Record to the store Application 171 Displaying a New Record 175 Using a Layout 176 Using a Stylesheet 177 Displaying Records 178 Adding Another Record 180 Editing Records 182 Beautifying the Display 187 Summary 189 Exercises 189 Chapter 7: Working with Databases 191 Displaying Items to the Customer 191 Getting the Items for Sale 192 Showing the Items for Sale 194 Creating a Shopping Cart 197 Designing the Shopping Cart 197 Creating the purchases Table 199 Creating the Purchase Model 200 Creating the Cart 203 Storing the Cart in a Session 205 Handling a Purchase 206 Displaying the Cart 209 Combining Purchases in the Cart 213 Clearing the Cart 216 Letting the User View the Cart Anytime 219 Summary 221 Exercises 222 xvi 02_069155 ftoc.qxp 10/23/06 8:02 PM Page xvii Contents Chapter 8: Validating and Testing 223 Validating the Presence of Data 223 Validating if