The Rails™ 4 Way
Total Page:16
File Type:pdf, Size:1020Kb
Praise for The Rails Way For intermediates and above, I strongly recommend adding this title to your tech- nical bookshelf. There is simply no other Rails title on the market at this time that offers the technical depth of the framework than The Rails™ 3 Way. — Mike Riley, Dr. Dobb’s Journal I highly suggest you get this book. Software moves fast, especially the Rails API, but I feel this book has many core API and development concepts that will be useful for a while to come. — Matt Polito, software engineer and member of Chicago Ruby User Group This book should live on your desktop if you’re a Rails developer. It’s nearly perfect in my opinion. — Luca Pette, developer The Rails™ 3 Way is likely to take you from being a haphazard poke-a- stick- at- it programmer to a deliberate, skillful, productive, and confi dent RoR developer. — Katrina Owen, JavaRanch I can positively say that it’s the single best Rails book ever published to date. By a long shot. — Antonio Cangiano, software engineer and technical evangelist at IBM psn-fernandez-all.indb i 5/9/14 10:07 AM This book is a great crash course in Ruby on Rails! It doesn’t just document the features of Rails, it fi lters everything through the lens of an experienced Rails developer— so you come out a pro on the other side. — Dirk Elmendorf, cofounder of Rackspace Inc. and Rails developer The key to The Rails Way is in the title. It literally covers the “way” to do almost everything with Rails. Writing a truly exhaustive reference to the most popular web application framework used by thousands of developers is no mean feat. A thankful community of developers that has struggled to rely on scant documentation will embrace The Rails Way with open arms. A tour de force! — Peter Cooper, editor, Ruby Inside: The Ruby Blog In the past year, dozens of Rails books have been rushed to publication. A handful are good. Most regurgitate rudimentary information easily found on the Web. Only this book provides both the broad and deep technicalities of Rails. Nascent and expert developers, I recommend you follow The Rails Way. — Martin Streicher, chief technology offi cer, McClatchy Interactive, former editor in chief of Linux Magazine Hal Fulton’s The Ruby Way has always been by my side as a reference while program- ming Ruby. Many times I had wished there was a book that had the same depth and attention to detail, only focused on the Rails framework. That book is now here and hasn’t left my desk for the past month. — Nate Klaiber, Ruby programmer I knew soon after becoming involved with Rails that I had found something great. Now, with Obie’s book, I have been able to step into Ruby on Rails development coming from .NET and be productive right away. The applications I have created I believe to be a much better quality due to the techniques I learned using Obie’s knowledge. — Robert Bazinet, InfoQ.com, .NET, and Ruby community editor and founding member of the Hartford Ruby Brigade Extremely well written; it’s a resource that every Rails programmer should have. Yes, it’s that good. — Reuven Lerner, Linux Journal columnist psn-fernandez-all.indb ii 5/9/14 10:07 AM THE RAILS™ 4 WAY psn-fernandez-all.indb iii 5/9/14 10:07 AM Addison-Wesley Professional Ruby Series Obie Fernandez, Series Editor Visit informit.com/ruby for a complete list of available products. he Addison-Wesley Professional Ruby Series provides readers with practical, Tpeople-oriented, and in-depth information about applying the Ruby platform to create dynamic technology solutions. The series is based on the premise that the need for expert reference books, written by experienced practitioners, will never be satisfied solely by blogs and the Internet. Make sure to connect with us! informit.com/socialconnect psn-fernandez-all.indb iv 5/9/14 10:07 AM THE RAILS™ 4 WAY Obie Fernandez Kevin Faustino Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City psn-fernandez-all.indb v 5/9/14 10:07 AM Many of the designations used by manufacturers and sellers to distinguish their products are claimed Editor- in-Chief as trademarks. Where those designations appear in this book, and the publisher was aware of a trade- Mark L. Taub mark claim, the designations have been printed with initial capital letters or in all capitals. Acquisitions Editor Debra Williams Cauley The authors and publisher have taken care in the preparation of this book but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is Managing Editor John Fuller assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. Full- Service Production Manager For information about buying this title in bulk quantities or for special sales opportunities (which may Julie B. Nahil include electronic versions; custom cover designs; and content particular to your business, training Editorial Assistant goals, marketing focus, or branding interests), please contact our corporate sales department at corp- Kim Boedigheimer [email protected] or (800) 382- 3419. Production Editor For government sales inquiries, please contact [email protected]. Scribe Inc. For questions about sales outside the United States, please contact [email protected]. Copy Editor Scribe Inc. Visit us on the web: informit.com/aw Indexer Scribe Inc. Cataloging- in- Publication Data is on fi le with the Library of Congress Proofreader Copyright © 2014 Pearson Education, Inc. Scribe Inc. Compositor All rights reserved. Printed in the United States of America. This publication is protected by copyright, Scribe Inc. and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, Cover Designer Chuti Prasertsith recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236- 3290. Parts of this book contain material excerpted from the Ruby and Rails source code and API doc- umentation, copyright © 2004– 2014 by David Heinemeier Hansson under the MIT license. Chapter 21 contains material excerpted from the RSpec source code and API documentation, copyright © 2005– 2014 by the RSpec Development Team. Rails and Ruby on Rails are trademarks of David Heinemeier Hansson. The MIT License reads: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation fi les (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is fur- nished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAM- AGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OR OTHER DEALINGS IN THE SOFTWARE. ISBN- 13: 978- 0- 321- 94427- 6 ISBN- 10: 0- 321- 94427- 5 Text printed in the United States on recycled paper at Courier in Westford, Massachusetts. First printing, June 2014 psn-fernandez-all.indb vi 5/9/14 10:07 AM Taylor, your hard work and dedication to your craft are an inspiration to me every day. I love you. psn-fernandez-all.indb vii 5/9/14 10:07 AM This page intentionally left blank Contents Foreword by Steve Klabnik xxxix Foreword to the Previous Edition by David Heinemeier Hansson xli Foreword to the Previous Edition by Yehuda Katz xliii Introduction xlv Acknowledgments li About the Authors liii Chapter 1 Rails Environments and Confi guration 1 1.1 Bundler 2 1.1.1 Gemfile 3 1.1.2 Installing Gems 5 1.1.3 Gem Locking 7 1.1.4 Packaging Gems 7 1.2 Startup and Application Settings 9 1.2.1 config/application.rb 9 1.2.2 Initializers 11 1.2.3 Additional Confi guration 16 1.2.4 Spring Application Preloader 17 1.3 Development Mode 18 1.3.1 Automatic Class Reloading 18 1.3.2 Eager Load 20 1.3.3 Error Reports 20 1.3.4 Caching 20 1.3.5 Raise Delivery Errors 21 ix psn-fernandez-all.indb ix 5/9/14 10:07 AM x Contents 1.3.6 Deprecation Notices 21 1.3.7 Pending Migrations Error Page 21 1.3.8 Assets Debug Mode 22 1.4 Test Mode 22 1.5 Production Mode 23 1.5.1 Assets 25 1.5.2 Asset Hosts 26 1.6 Confi guring a Database 26 1.7 Confi guring Application Secrets 27 1.8 Logging 29 1.8.1 Rails Log Files 30 1.8.2 Tagged Logging 32 1.8.3 Log File Analysis 32 1.9 Conclusion 35 Chapter 2 Routing 37 2.1 The Two Purposes of Routing 38 2.2 The routes.rb File 39 2.2.1 Regular Routes 40 2.2.2 Constraining Request Methods 41 2.2.3 URL Patterns 42 2.2.4 Segment Keys 43 2.2.5 Spotlight on the :id Field 44 2.2.6 Optional Segment Keys 44 2.2.7 Redirect Routes 45 2.2.8 The Format Segment 46 2.2.9 Routes as Rack Endpoints 48 2.2.10 Accept Header 48 2.2.11