Advanced Rails Recipies.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Prepared exclusively for Jeanne McDade Beta Book Agile publishing for agile developers The book you’re reading is still under development. As an experiment, we’re releasing this copy well before we normally would. That way you’ll be able to get this content a couple of months before it’s avail- able in finished form, and we’ll get feedback to make the book even better. The idea is that everyone wins! Be warned. The book has not had a full technical edit, so it will con- tain errors. It has not been copyedited, so it will be full of typos. And there’s been no effort spent doing layout, so you’ll find bad page breaks, over-long lines, incorrect hyphenations, and all the other ugly things that you wouldn’t expect to see in a finished book. We can’t be held liable if you use this book to try to create a spiffy application and you somehow end up with a strangely shaped farm implement instead. Despite all this, we think you’ll enjoy it! Throughout this process you’ll be able to download updated PDFs from your personal home page at http://www.pragprog.com/my_account (you’ll need to create an account if you don’t already have one). When the book is complete, you’ll get the final version (and subsequent updates) from the same address. In the meantime, we’d appreciate you sending us your feedback at http://pragprog.com/titles/fr_arr/errata. Thank you for taking part in this experiment. Dave and Andy Prepared exclusively for Jeanne McDade Advanced Rails Recipes Mike Clark and the Rails Community The Pragmatic Bookshelf Raleigh, North Carolina Dallas, Texas Prepared exclusively for Jeanne McDade Many of the designations used by manufacturers and sellers to distinguish their prod- ucts 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.pragprog.com Copyright © 2008 Mike Clark. 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-10: 0-9787392-2-1 ISBN-13: 978-0-9787392-2-5 Printed on acid-free paper with 50% recycled, 15% post-consumer content. B1.02 printing, January 2, 2008 Version: 2008-1-2 Prepared exclusively for Jeanne McDade Contents 1 Introduction 9 1.1 What Makes a Good Recipe Book? ............. 9 1.2 What Makes This an Advanced Recipe Book? ...... 10 1.3 Who’s It For? ......................... 10 1.4 Who’s Talking? ........................ 11 1.5 Rails Version ......................... 11 1.6 Resources ........................... 11 1.7 Acknowledgments ...................... 12 1.8 Tags and Thumb tabs .................... 13 Part I—REST and Routes Recipes 14 1. Putting A Resource On The Web .............. 15 2. Adding Your Own REST Actions (Or Not) ......... 20 3. Authenticating REST Clients ................ 23 4. Custom Response Formats ................. 29 5. Catch All 404s ........................ 33 Part II—Search Recipes 36 6. Improve SEO with Dynamic Meta Tags .......... 37 7. Full-Text Search with Ferret ................ 40 8. Active Record on Solr .................... 45 Part III—Database Recipes 50 9. Adding Foreign Key Constraints .............. 51 10. Write Your Own Custom Validations ............ 54 11. Analyzing SQL Queries ................... 58 12. Taking Advantage of Master/Slave Databases ...... 61 Prepared exclusively for Jeanne McDade CONTENTS 6 Part IV—User Interface Recipes 64 13. Replacing In-View Raw JavaScript with RJS ....... 65 14. Handling Multiple Models In One Form .......... 67 15. Simplifying Controllers With a Presenter ......... 74 16. Validating Required Form Fields Inline .......... 79 17. Creating a Wizard ...................... 83 18. Updating Partial Resources with Ajax ........... 92 19. Uploading Images and Creating Thumbnails ....... 95 20. Decouple Your JavaScript with Low Pro .......... 102 Part V—Design Recipes 108 21. Freshening Up Your Models With Scope ......... 109 22. Keeping Forms Dry and Flexible .............. 115 23. Prevent Train Wrecks with Delegate ............ 120 24. Creating Meaningful Relationships Through Proxies . 123 Part VI—Asynchronous Recipes 126 25. Processing an Asynchronous Workflow .......... 127 26. Off-Loading Long-Running Tasks to BackgrounDRb . 133 Part VII—E-mail Recipes 141 27. Validating E-mail Addresses ................ 142 28. Receiving E-mail Reliably via POP or IMAP ........ 145 29. Keeping E-mail Addresses Up To Date .......... 151 Part VIII—Console Snacks 156 30. Writin’ Console Methods ................... 157 31. Console Loggin’ ........................ 159 32. Playin’ in the Sandbox .................... 161 33. Accessin’ Helpers ....................... 162 34. Shortcuttin’ the Console ................... 163 Part IX—Testing 165 35. Creating Your Own Rake Test Tasks ............ 166 36. Testing JavaScript With Selenium ............. 169 37. Mocking With a Safety Net ................. 174 38. Getting Started with BDD .................. 176 Report erratum Prepared exclusively for Jeanne McDade this copy is (B1.02 printing, January 2, 2008) CONTENTS 7 39. Describing Behaviour from the Outside-In With RSpec . 181 40. Reducing Dependencies with Mocks ............ 188 41. Fixtures Without Frustration ................ 192 42. Tracking Test Coverage with RCov ............. 196 43. Testing HTML Validity .................... 200 Part X—Performance and Scalability Recipes 204 44. Looking Up Constant Data ................. 205 45. Serving Page Caches to Facebook ............. 209 46. Profiling In The Browser ................... 211 47. Caching Up With the Big Guys ............... 215 48. Dynamically Updating Cached Pages ........... 222 Part XI—Security Recipes 226 49. Flipping On SSL ....................... 227 50. Locking Down Sensitive Data ................ 230 Part XII—Deployment and Capistrano Recipes 232 51. Custom Maintenance Pages ................. 233 52. Running Multi-Stage Deployments ............ 237 53. Creating New Environments ................ 240 54. Managing Plugin Versions .................. 243 55. Safeguarding the Launch Codes .............. 246 56. Config Files On-The-Fly ................... 247 57. Preserving Files Between Deployments .......... 249 58. Responding To Remote Prompts .............. 251 59. Generating Custom Error Pages .............. 253 Part XIII—Big-Picture Recipes 257 60. Avoid Starting From Scratch ................ 258 61. Fail Early ........................... 261 62. Analyzing Your Log Files .................. 263 63. Formatting Dates and Times ................ 268 64. Geocoding to Find Things By Location .......... 271 65. Giving Users Their Own Subdomain ............ 277 66. Tunneling Back to Your Application ............ 281 67. Monitoring (and Repairing) Processes with Monit . 285 Report erratum Prepared exclusively for Jeanne McDade this copy is (B1.02 printing, January 2, 2008) CONTENTS 8 A Bibliography 288 Index 289 Report erratum Prepared exclusively for Jeanne McDade this copy is (B1.02 printing, January 2, 2008) Chapter 1 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 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 Advanced 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 techniques they contain) are extracted from my own work and from the work of other “great chefs” of Rails around the community. 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 Prepared exclusively for Jeanne McDade WHAT MAKES THIS AN ADVANCED RECIPE BOOK? 10 should walk away with a new level of Rails understanding to go with a huge list of successfully implemented hot new application features. Not all of these recipes are full meals. To spice things up, I’ve included a number of smaller side dishes, which I’ve called snacks. Typically one or two pages long, these snacks will help satisfy those cravings we all get between meals. 1.2 What Makes This an Advanced Recipe Book? Sushi is a treat for the eyes, as much as it’s a treat for my taste buds. The sushi chefs behind the bar of my favorite local spot take great pride in making not only delicious dishes, but exquisite looking ones as well.