Rails Recipes.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Prepared exclusively for Eric Dean Rails Recipes Chad Fowler The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Prepared exclusively for Eric Dean Pragmatic helf Book s Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://www.pragmaticprogrammer.com Copyright © 2006 The Pragmatic Programmers LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmit- ted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN 0-9776166-0-6 Printed on acid-free paper with 85% recycled, 30% post-consumer content. P2.0 printing, July, 2006 Version: 2006-7-6 Prepared exclusively for Eric Dean Contents Introduction vii What Makes a Good Recipe Book? ................ vii Who’s It For? ............................ viii Rails Version ............................. viii Resources .............................. viii Acknowledgments .......................... ix Tags and Thumb tabs ....................... xi Part I—User Interface Recipes 1 1. In-Place Form Editing .................... 2 2. Making Your Own JavaScript Helper ........... 8 3. Showing a Live Preview ................... 15 4. Autocomplete a Text Field .................. 18 5. Creating a Drag-and-Drop Sortable List ......... 20 6. Update Multiple Elements with One Ajax Request . 26 7. Lightning-Fast JavaScript Autocompletion ........ 31 8. Cheap & Easy Theme Support ............... 36 9. Trim Static Pages with Ajax ................. 37 10. Smart Pluralization ..................... 38 11. Debugging Ajax ........................ 39 12. Creating a Custom Form Builder ............. 41 13. Make Pretty Graphs ..................... 45 Part II—Database Recipes 49 14. Rails without a Database .................. 50 15. Connecting to Multiple Databases ............. 55 16. Integrating with Legacy Databases ............. 63 17. DRY Up Your Database Configuration ........... 66 18. Self-referential Many-to-Many Relationships ....... 68 19. Tagging Your Content .................... 71 Prepared exclusively for Eric Dean CONTENTS v 20. Versioning Your Models ................... 78 21. Converting to Migration-Based Schemas ......... 83 22. Many-to-Many Relationships with Extra Data ...... 89 23. Polymorphic Associations—has_many :whatevers . 94 24. Add Behavior to Active Record Associations ....... 99 25. Dynamically Configure Your Database .......... 103 26. Use Active Record Outside of Rails ............ 104 27. Perform Calculations on Your Model Data ........ 105 28. DRY Up Active Record Code with Scoping ........ 107 29. Make Dumb Data Smart with composed_of() ....... 108 30. Safely Use Models in Migrations .............. 112 Part III—Controller Recipes 114 31. Authenticating Your Users ................. 115 32. Authorizing Users with Roles ................ 121 33. Cleaning Up Controllers with Postback Actions . 126 34. Monitor Expiring Sessions ................. 127 35. Rendering Comma-Separated Values from Your Actions 129 36. Make Your URLs Meaningful (and Pretty) ......... 131 37. Stub Out Authentication .................. 136 38. Convert to Active Record Sessions ............. 137 39. Write Code That Writes Code ................ 138 40. Manage a Static Site with Rails .............. 143 Part IV—Testing Recipes 144 41. Creating Dynamic Test Fixtures .............. 145 42. Extracting Test Fixtures from Live Data ......... 150 43. Testing Across Multiple Controllers ............ 155 44. Write Tests for Your Helpers ................ 161 Part V—Big-Picture Recipes 163 45. Automating Development with Your Own Generators . 164 46. Continuously Integrate Your Code Base ......... 171 47. Getting Notified of Unhandled Exceptions ........ 176 48. Creating Your Own Rake Tasks .............. 180 49. Dealing with Time Zones .................. 186 50. Living on the Edge (of Rails Development) ........ 192 51. Syndicate Your Site with RSS ................ 196 52. Making Your Own Rails Plugins .............. 204 Report erratum Prepared exclusively for Eric Dean CONTENTS vi 53. Secret URLs .......................... 208 54. Quickly Inspect Your Sessions’ Contents ......... 212 55. Sharing Models between Your Applications ........ 214 56. Generate Documentation for Your Application . 216 57. Processing Uploaded Images ................ 217 58. Easily Group Lists of Things ................ 221 59. Keeping Track of Who Did What .............. 222 60. Distributing Your Application As One Directory Tree . 227 61. Adding Support for Localization .............. 230 62. The Console Is Your Friend ................. 236 63. Automatically Save a Draft of a Form ........... 238 64. Validating Non–Active Record Objects ........... 241 65. Easy HTML Whitelists .................... 244 66. Adding Simple Web Services to Your Actions ....... 247 Part VI—Email Recipes 252 67. Send Gracefully Degrading Rich-Content Emails . 253 68. Testing Incoming Email ................... 257 69. Sending Email with Attachments ............. 265 70. Handling Bounced Email .................. 268 Part VII—Appendix 275 A Resources 276 A.1 Bibliography ......................... 276 A.2 Source Code .......................... 276 Report erratum Prepared exclusively for Eric Dean Introduction What Makes a Good Recipe Book? If I were to buy a real recipe book—you know, a book about cooking food—I wouldn’t be looking for a book that tells me how to dice vegeta- bles or how to use a skillet. I can find that kind of information in an overview about cooking. A recipe book is about how to make food you might not be able to easily figure out how to make on your own. It’s about skipping the trial and error and jumping straight to a solution that works. Sometimes it’s even about making food you never imagined you could make. If you want to learn how to make great Indian food, you buy a recipe book by a great Indian chef and follow his or her directions. You’re not just buying any old solution. You’re buying a solution you can trust to be good. That’s why famous chefs sell lots and lots of books. People want to make food that tastes good, and these chefs know how to make (and teach you how to make) food that tastes good. Good recipe books do teach you techniques. Sometimes they even teach you about new tools. But they teach these skills within the context and with the end goal of making something—not just to teach them. My goal for Rails Recipes is to teach you how to make great stuff with Rails and to do it right on your first try. These recipes and the tech- niques herein are extractions from my own work and from the “great chefs” of Rails: the Rails core developer team, the leading trainers and authors, and the earliest of early adopters. I also hope to show you not only how to do things but to explain why they work the way they do. After reading through the recipes, you should walk away with a new level of Rails understanding to go with a huge list of successfully implemented hot new application features. Prepared exclusively for Eric Dean WHO’S IT FOR? viii Not all of these recipes are long and involved. To spice things up, I’ve included a number of smaller offerings, which I’ve called snacks. Typi- cally one or two pages long, these snacks will help satisfy those cravings we all get between meals. Who’s It For? Rails Recipes is for people who understand Rails and now want to see how an experienced Rails developer would attack specific problems. Like with a real recipe book, you should be able to flip through the table of contents, find something you need to get done, and get from start to finish in a matter of minutes. I’m going to assume that you know the basics or that you can find them in a tutorial or an online reference. When you’re busy trying to make something, you don’t have spare time to read through introduc- tory material. So if you’re still in the beginning stages of learning Rails, be sure to have a copy of Agile Web Development with Rails [TH05] and a bookmark to the Rails API documentation handy.1 Rails Version The examples in this book, except where noted, should work with Rails 1.0 or higher. Several recipes cover new features that were released with Rails 1.1. Resources The best place to go for Rails information is the Rails website.2 From there, you can find the mailing lists, IRC channels, and weblogs. The Pragmatic Programmers have also set up a forum for Rails Recipes readers to discuss the recipes, help each other with problems, expand on the solutions, and even write new recipes. While Rails Recipes was in beta, the forum served as such a great resource for ideas that more than one reader-posted