Ruby for Rails
Total Page:16
File Type:pdf, Size:1020Kb
Ruby for Rails Ruby for Rails RUBY TECHNIQUES FOR RAILS DEVELOPERS DAVID A. BLACK MANNING Greenwich (74° w. long.) For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 209 Bruce Park Avenue Fax:(203) 661-9018 Greenwich, CT 06830 email: [email protected] ©2006 Manning Publications. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books they publish printed on acid-free paper, and we exert our best efforts to that end. Manning Publications Co. Copyeditor: Liz Welch 209 Bruce Park Avenue Typesetter: Gordan Salinovic Greenwich, CT 06830 Cover designer: Leslie Haimes ISBN 1932394699 Printed in the United States of America 12345678910–VHG–10 090807 06 for n in nephews + nieces which is to say: Annie, David, Elizabeth, Rebecca, and Robert, with all my love. You’re all absolutely amazing, and I adore you. brief contents PART ITHE RUBY/RAILS LANDSCAPE ...........................1 1 ■ How Ruby works 3 2 ■ How Rails works 33 3 ■ Ruby-informed Rails development 67 PART II RUBY BUILDING BLOCKS ................................93 4 ■ Objects and variables 95 5 ■ Organizing objects with classes 121 6 ■ Modules and program organization 154 7 ■ The default object (self) and scope 177 8 ■ Control flow techniques 206 PART III BUILT-IN CLASSES AND MODULES ...............231 9 ■ Built-in essentials 233 10 ■ Scalar objects 257 11 ■ Collections, containers, and enumerability 277 vii viii BRIEF CONTENTS 12 ■ Regular expressionsand regexp-based string operations 312 13 ■ Ruby dynamics 337 PART IV RAILS THROUGH RUBY, RRRRRRRRIRUBY THROUGH RAILS ............................. 369 14 ■ (Re)modeling the R4RMusic application universe 371 15 ■ Programmatically enhancing ActiveRecord models 392 16 ■ Enhancing the controllers and views 422 17 ■ Techniques for exploring the Rails source code 455 appendix ■ Ruby and Rails installation and resources 471 contents foreword xix preface xxi acknowledgments xxiii about this book xxvi about the cover illustration xxxii PART 1THE RUBY/RAILS LANDSCAPE ...........................1 How Ruby works 3 1 1.1 The mechanics of writing a Ruby program 4 Getting the preliminaries in place 5 ■ A Ruby literacy bootstrap guide 5 ■ A brief introduction to method calls and Ruby objects 7 Writing and saving a sample program 8 ■ Feeding the program to Ruby 9 ■ Keyboard and file input 11 ■ One program, multiple files 14 1.2 Techniques of interpreter invocation 15 Command-line switches 16 ■ A closer look at interactive Ruby interpretation with irb 20 1.3 Ruby extensions and programming libraries 21 Using standard extensions and libraries 21 ■ Using C extensions 22 ■ Writing extensions and libraries 23 ix x CONTENTS 1.4 Anatomy of the Ruby programming environment 24 The layout of the Ruby source code 24 ■ Navigating the Ruby installation 25 ■ Important standard Ruby tools and applications 27 1.5 Summary 31 How Rails works 33 2 2.1 Inside the Rails framework 34 A framework user’s–eye view of application development 35 Introducing the MVC framework concept 36 Meet MVC in the (virtual) flesh 37 2.2 Analyzing Rails’ implementation of MVC 38 2.3 A Rails application walk-through 41 Introducing R4RMusic, the music-store application 42 Modeling the first iteration of the music-store domain 43 Identifying and programming the actions 50 ■ Designing the views 53 ■ Connecting to the application 58 2.4 Tracing the lifecycle of a Rails run 59 Stage 1: server to dispatcher 61 ■ Stage 2: dispatcher to controller 62 ■ Stage 3: performance of a controller action 62 ■ Stage 4: the fulfillment of the view 65 2.5 Summary 65 Ruby-informed Rails development 67 3 3.1 A first crack at knowing what your code does 69 Seeing Rails as a domain-specific language 70 ■ Writing program code with a configuration flavor 73 ■ YAML and configuration that’s actually programming 75 3.2 Starting to use Ruby to do more in your code 77 Adding functionality to a controller 79 ■ Deploying the Rails helper files 80 ■ Adding functionality to models 82 3.3 Accomplishing application-related skills and tasks 85 Converting legacy data to ActiveRecord 85 The irb-based Rails application console 89 3.4 Summary 90 CONTENTS xi PART 2RUBY BUILDING BLOCKS .................................93 Objects and variables 95 4 4.1 From “things” to objects 96 Introducing object-oriented programming 97 ■ I, object! 98 Modeling objects more closely: the behavior of a ticket 103 4.2 The innate behaviors of an object 108 Identifying objects uniquely with the object_id method 109 Querying an object’s abilities with the respond_to? method 110 Sending messages to objects with the send method 111 4.3 Required, optional, and default-valued arguments 112 Required and optional arguments 112 ■ Default values for arguments 113 ■ Order of arguments 114 4.4 Local variables and variable assignment 115 Variable assignment in depth 117 ■ Local variables and the things that look like them 119 4.5 Summary 120 Organizing objects with classes 121 5 5.1 Classes and instances 122 A first class 123 ■ Instance variables and object state 126 5.2 Setter methods 130 The equal sign (=) in method names 131 ActiveRecord properties and other =-method applications 133 5.3 Attributes and the attr_* method family 136 Automating the creation of attribute handlers 137 ■ Two (getter/ setter) for one 138 ■ Summary of attr_* methods 139 5.4 Class methods and the Class class 140 Classes are objects too! 140 ■ When, and why, to write a class method 141 ■ Class methods vs. instance methods, clarified 143 The Class class and Class.new 144 5.5 Constants up close 145 Basic usage of constants 145 ■ Reassigning vs. modifying constants 146 xii CONTENTS 5.6 Inheritance 148 Inheritance and Rails engineering 149 ■ Nature vs. nurture in Ruby objects 151 5.7 Summary 153 Modules and program organization 154 6 6.1 Basics of module creation and use 155 A module encapsulating “stack-like-ness” 157 ■ Mixing a module into a class 158 ■ Leveraging the module further 160 6.2 Modules, classes, and method lookup 163 Illustrating the basics of method lookup 163 ■ Defining the same method more than once 166 ■ Going up the method search path with super 168 6.3 Class/module design and naming 170 Mix-ins and/or inheritance 171 ■ Modular organization in Rails source and boilerplate code 173 6.4 Summary 176 The default object (self) and scope 177 7 7.1 Understanding self, the current/default object 179 Who gets to be self, and where 179 ■ Self as default receiver of messages 184 ■ Instance variables and self 186 7.2 Determining scope 188 Global scope and global variables 188 ■ Local scope 191 Scope and resolution of constants 194 7.3 Deploying method access rules 197 Private methods 197 ■ Private methods as ActionController access protection 199 ■ Protected methods 201 7.4 Writing and using top-level methods 203 Defining a top-level method 203 ■ Predefined (built-in) top-level methods 204 7.5 Summary 205 Control flow techniques 206 8 8.1 Conditional code execution 207 The if keyword and friends 208 ■ Conditional modifiers 211 Case statements 211 CONTENTS xiii 8.2 Repeating actions with loops 215 Unconditional looping with the loop method 215 Conditional looping with the while and until keywords 216 Looping based on a list of values 218 8.3 Code blocks, iterators, and the yield keyword 219 The basics of yielding to a block 219 ■ Performing multiple iterations 222 ■ Using different code blocks 223 More about for 223 8.4 Error handling and exceptions 225 Raising and rescuing exceptions 225 ■ Raising exceptions explicitly 227 ■ Creating your own exception classes 228 8.5 Summary 230 PART 3BUILT-IN CLASSES AND MODULES ...................231 Built-in essentials 233 9 9.1 Ruby’s literal constructors 234 9.2 Recurrent syntactic sugar 236 Special treatment of += 237 9.3 Methods that change their receivers (or don’t) 238 Receiver-changing basics 239 ■ bang (!) methods 240 Specialized and extended receiver-changing in ActiveRecord objects 241 9.4 Built-in and custom to_* (conversion) methods 242 Writing your own to_* methods 243 9.5 Iterators reiterated 244 9.6 Boolean states, Boolean objects, and nil 245 True and false as states 246 ■ true and false as objects 248 The special object nil 249 9.7 Comparing two objects 251 Equality tests 251 ■ Comparisons and the Comparable module 252 9.8 Listing an object’s methods 253 Generating filtered and selective method lists 254 9.9 Summary 255 xiv CONTENTS Scalar objects 257 10 10.1 Working with strings 258 String basics 258 ■ String operations 260 Comparing strings 265 10.2 Symbols and their uses 267 Key differences between symbols and strings 267 Rails-style method arguments, revisited 268 10.3 Numerical objects 270 Numerical classes 270 ■ Performing arithmetic operations 271 10.4 Times and dates 272 10.5 Summary 275 Collections, containers, and enumerability 277 11 11.1 Arrays