Rails Recipes
Total Page:16
File Type:pdf, Size:1020Kb
Rails Recipes Chad Fowler The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas P r a g m a t i c B o o k s h e l f 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. B1.3 printing, March 16, 2006 Version: 2006-4-11 Contents 1 Introduction 1 1.1 What Makes a Good Recipe Book? ............. 1 1.2 Who’s It For? ......................... 2 1.3 Rails Version ......................... 2 1.4 Resources ........................... 2 1.5 Acknowledgments ...................... 3 1.6 Tags and Thumbtabs .................... 5 Part I—User Interface Recipes 6 1. In-Place Form Editing .................... 7 2. Making Your Own JavaScript Helper ........... 13 3. Live Preview .......................... 20 4. Live Search .......................... 23 5. Creating a Drag-and-Drop Sortable List ......... 26 6. Update Multiple Page Elements With One Ajax Request 32 7. Lightning-Fast JavaScript Auto-completion . 38 8. Cheap and Easy Theme Support .............. 43 9. Use Ajax To Trim Fat, Static Pages ............ 44 10. Smart Pluralization ..................... 45 11. Debugging Ajax ........................ 46 12. Creating a Custom Form Builder ............. 48 13. Make Pretty Graphs ..................... 52 Part II—Database Recipes 56 14. Rails Without A Database .................. 57 15. Connecting to Multiple Databases ............. 61 16. Integrating with Legacy Databases ............. 69 17. DRY Up Your Database Configuration ........... 72 18. Self-referential Many-to-Many Relationships . 74 19. Tagging ............................ 77 CONTENTS vi 20. Versioning Your ActiveRecord Models ........... 84 21. Convert an Existing Application to Migrations . 89 22. Many to Many Relationships Where the Relationship Itself Has Data 94 23. Polymorphic Associations - has_many :whatevers . 99 24. Adding Behavior to Your ActiveRecord Associations . 104 25. Dynamic Database Config .................. 108 26. Use ActiveRecord Outside of Rails ............. 109 27. Perform Calculations on Yor Model Data ......... 110 28. DRY Up Your ActiveRecord Code With Scoping . 113 29. Make Dumb Data Smart with composed_of . 114 30. Safely Use Models in Migrations .............. 118 Part III—Controller Recipes 120 31. Authentication ........................ 121 32. Role-Based Authorization .................. 127 33. Cleaning Up Controllers with Postback Actions . 132 34. Keep An Eye On Your Session Expiry ........... 133 35. Rendering Comma Separated Values From Your Actions 135 36. Make your URLs Meaningful (and pretty) ......... 137 37. Stub Out Authentication .................. 142 38. Convert Your Sessions To ActiveRecord .......... 143 39. Write Code That Writes Code ................ 144 40. Manage a Static Site With Rails .............. 146 Part IV—Testing Recipes 147 41. Creating Dynamic Test Fixtures .............. 148 42. Extracting Test Fixtures From Live Data ......... 153 43. Testing Across Multiple Controllers ............ 157 44. Write Tests for Your Helpers ................ 164 Part V—Big Picture Recipes 166 45. Automating Development With Your Own Generators . 167 46. Continuous Integration ................... 175 47. Getting Notified of Unhandled Exceptions ........ 180 48. Creating Your Own Rake Tasks .............. 185 49. Dealing With Time-zones .................. 191 50. Living On The Edge (of Rails Development) ........ 197 51. Syndicate Your Site With RSS ............... 201 52. Making Your Own Rails Plugins .............. 209 Report erratum CONTENTS vii 53. Secret URLs .......................... 213 54. Quickly Inspect Your Sessions’ Contents ......... 217 55. Sharing Models Between Your Applications . 219 56. Generate Documentation For Your Application . 222 57. Processing Uploaded Images ................ 223 58. Easily Group Lists of Things ................ 227 59. Keeping Track of Who Did What .............. 228 60. Distributing Your Application As One Directory Tree . 233 61. Adding Support for Localization .............. 236 62. The Console Is Your Friend ................. 242 63. Automatically Save a Draft of a Form ........... 244 64. Validating Non-ActiveRecord Objects ........... 247 65. Easy HTML Whitelists .................... 250 66. Adding Simple Web Services To Your Actions . 253 Part VI—E-Mail Recipes 258 67. Send Gracefully Degrading Rich-Content Emails . 259 68. Testing Incoming Email ................... 264 69. Sending Email With Attachments ............. 273 70. Handling Bounced Email .................. 277 Part VII—Appendix 284 A Resources 285 A.1 Bibliography ......................... 285 A.2 Source Code .......................... 285 Report erratum Introduction 1.1 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 things 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 things 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 things within the context and 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 therein are extractions from my own work and from the “great chefs” of Rails: the core Rails 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 WHO’S IT FOR? 2 should walk away with a new level of Rails understanding to go with a huge list of successfully implemented hot new application features. 1.2 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 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 [TH05] and a bookmark to the Rails API doc- umentation1 handy. 1.3 Rails Version The examples in this book, except where noted, should work with Rails 1.0 or higher. There are several recipes that cover new features that were released with Rails 1.1. 1.4 Resources The best place to go for Rails information is the Rails website: http://www.rubyonrails.org. 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 recipe made it into the book! You can find the forum at: http://fora.pragprog.com/rails-recipes. You can find the book’s errata list at: http://books.pragprog.com/titles/fr_rr/errata. If you submit any problems you find, we’ll list them there. 1http://api.rubyonrails.org Report erratum ACKNOWLEDGMENTS 3 You’ll find links to the source code for almost all the book’s examples at http://www.pragmaticprogrammer.com/titles/fr_rr/code.html. If you’re reading the PDF version of this book, you can report an error on a page by clicking the erratum link at the bottom of the page, and you can get to the source code of an example by clicking on the gray lozenge containing the code’s file name that appears before the listing. 1.5 Acknowledgments Dave Thomas, like it or not, is a mentor and role model to a constantly growing segment of our industry—particularly within the Ruby world. I can’t imagine writing a book for another publisher. Anything else would undoubtedly be a huge step backward.