Home > Store

Design Patterns in Ruby

Register your product to gain access to bonus material or receive a coupon.

Design Patterns in Ruby

eBook

  • Your Price: $43.99
  • List Price: $54.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Description

  • Copyright 2008
  • Pages: 384
  • Edition: 1st
  • eBook
  • ISBN-10: 0-13-279998-7
  • ISBN-13: 978-0-13-279998-0

Praise for Design Patterns in Ruby

"Design Patterns in Ruby documents smart ways to resolve many problems that Ruby developers commonly encounter. Russ Olsen has done a great job of selecting classic patterns and augmenting these with newer patterns that have special relevance for Ruby. He clearly explains each idea, making a wealth of experience available to Ruby developers for their own daily work."

—Steve Metsker, Managing Consultant with Dominion Digital, Inc.

"This book provides a great demonstration of the key 'Gang of Four' design patterns without resorting to overly technical explanations. Written in a precise, yet almost informal style, this book covers enough ground that even those without prior exposure to design patterns will soon feel confident applying them using Ruby. Olsen has done a great job to make a book about a classically 'dry' subject into such an engaging and even occasionally humorous read."

—Peter Cooper

"This book renewed my interest in understanding patterns after a decade of good intentions. Russ picked the most useful patterns for Ruby and introduced them in a straightforward and logical manner, going beyond the GoF's patterns. This book has improved my use of Ruby, and encouraged me to blow off the dust covering the GoF book."

—Mike Stok

"Design Patterns in Ruby is a great way for programmers from statically typed objectoriented languages to learn how design patterns appear in a more dynamic, flexible language like Ruby."

—Rob Sanheim, Ruby Ninja, Relevance

Most design pattern books are based on C++ and Java. But Ruby is different—and the language's unique qualities make design patterns easier to implement and use. In this book, Russ Olsen demonstrates how to combine Ruby's power and elegance with patterns, and write more sophisticated, effective software with far fewer lines of code.

After reviewing the history, concepts, and goals of design patterns, Olsen offers a quick tour of the Ruby language—enough to allow any experienced software developer to immediately utilize patterns with Ruby. The book especially calls attention to Ruby features that simplify the use of patterns, including dynamic typing, code closures, and "mixins" for easier code reuse.

Fourteen of the classic "Gang of Four" patterns are considered from the Ruby point of view, explaining what problems each pattern solves, discussing whether traditional implementations make sense in the Ruby environment, and introducing Ruby-specific improvements. You'll discover opportunities to implement patterns in just one or two lines of code, instead of the endlessly repeated boilerplate that conventional languages often require.

Design Patterns in Ruby also identifies innovative new patterns that have emerged from the Ruby community. These include ways to create custom objects with metaprogramming, as well as the ambitious Rails-based "Convention Over Configuration" pattern, designed to help integrate entire applications and frameworks.

Engaging, practical, and accessible, Design Patterns in Ruby will help you build better software while making your Ruby programming experience more rewarding.

Sample Content

Table of Contents

Foreword xvii

Preface xix

Acknowledgments xxv

About the Author xxvii

PART I: Patterns and Ruby 1

Chapter 1: Building Better Programs with Patterns 3

The Gang of Four 4

Patterns for Patterns 4

Separate Out the Things That Change from Those That Stay the Same 5

Program to an Interface, Not an Implementation 5

Prefer Composition over Inheritance 7

Delegate, Delegate, Delegate 12

You Ain't Gonna Need It 13

Fourteen Out of Twenty-Three 15

Patterns in Ruby? 17

Chapter 2: Getting Started with Ruby 19

Interactive Ruby 20

Saying Hello World 20

Variables 23

Fixnums and Bignums 24

Floats 26

There Are No Primitives Here 26

But Sometimes There Is No Object 27

Truth, Lies, and nil 28

Decisions, Decisions 30

Loops 32

More about Strings 34

Symbols 37

Arrays 38

Hashes 40

Regular Expressions 40

A Class of Your Own 41

Getting at the Instance Variables 43

An Object Asks: Who Am I? 46

Inheritance, Subclasses, and Superclasses 46

Argument Options 47

Modules 49

Exceptions 52

Threads 53

Managing Separate Source Files 54

Wrapping Up 55

PART II: Patterns in Ruby 57

Chapter 3: Varying the Algorithm with the Template Method 59

Keeping Up with What Life Throws at You 60

Separate the Things That Stay the Same 61

Discovering the Template Method Pattern 65

Hook Methods 66

But Where Are All the Declarations? 68

Types, Safety, and Flexibility 69

Unit Tests Are Not Optional 71

Using and Abusing the Template Method Pattern 73

Templates in the Wild 74

Wrapping Up 75

Chapter 4: Replacing the Algorithm with the Strategy 77

Delegate, Delegate, and Delegate Again 78

Sharing Data between the Context and the Strategy 80

Duck Typing Yet Again 82

Procs and Blocks 84

Quick-and-Dirty Strategies 88

Using and Abusing the Strategy Pattern 90

The Strategy Pattern in the Wild 90

Wrapping Up 92

Chapter 5: Keeping Up with the Times with the Observer 95

Staying Informed 95

A Better Way to Stay Informed 97

Factoring Out the Observable Support 100

Code Blocks as Observers 104

Variations on the Observer Pattern 105

Using and Abusing the Observer Pattern 106

Observers in the Wild 108

Wrapping Up 109

Chapter 6: Assembling the Whole from the Parts with the Composite 111

The Whole and the Parts 112

Creating Composites 114

Sprucing Up the Composite with Operators 118

An Array as a Composite? 119

An Inconvenient Difference 120

Pointers This Way and That 120

Using and Abusing the Composite Pattern 122

Composites in the Wild 123

Wrapping Up 125

Chapter 7: Reaching into a Collection with the Iterator 127

External Iterators 127

Internal Iterators 130

Internal Iterators versus External Iterators 131

The Inimitable Enumerable 133

Using and Abusing the Iterator Pattern 134

Iterators in the Wild 136

Wrapping Up 140

Chapter 8: Getting Things Done with Commands 143

An Explosion of Subclasses 144

An Easier Way 145

Code Blocks as Commands 147

Commands That Record 148

Being Undone by a Command 151

Queuing Up Commands 154

Using and Abusing the Command Pattern 154

The Command Pattern in the Wild 155

ActiveRecord Migrations 155

Madeleine 156

Wrapping Up 160

Chapter 9: Filling in the Gaps with the Adapter 163

Software Adapters 164

The Near Misses 167

An Adaptive Alternative? 168

Modifying a Single Instance 170

Adapt or Modify? 172

Using and Abusing the Adapter Pattern 173

Adapters in the Wild 173

Wrapping Up 174

Chapter 10: Getting in Front of Your Object with a Proxy 175

Proxies to the Rescue 176

The Protection Proxy 178

Remote Proxies 179

Virtual Proxies Make You Lazy 180

Eliminating That Proxy Drudgery 182

Message Passing and Methods 183

The method_missing Method 184

Sending Messages 185

Proxies without the Tears 185

Using and Abusing Proxies 189

Proxies in the Wild 190

Wrapping Up 192

Chapter 11: Improving Your Objects with a Decorator 193

Decorators: The Cure for Ugly Code 193

Formal Decoration 200

Easing the Delegation Blues 200

Dynamic Alternatives to the Decorator Pattern 201

Wrapping Methods 202

Decorating with Modules 202

Using and Abusing the Decorator Pattern 204

Decorators in the Wild 205

Wrapping Up 206

Chapter 12: Making Sure There Is Only One with the Singleton 207

One Object, Global Access 207

Class Variables and Methods 208

Class Variables 208

Class Methods 209

A First Try at a Ruby Singleton 211

Managing the Single Instance 212

Making Sure There Is Only One 213

The Singleton Module 214

Lazy and Eager Singletons 214

Alternatives to the Classic Singleton 215

Global Variables as Singletons 215

Classes as Singletons 216

Modules as Singletons 218

A Safety Harness or a Straitjacket? 219

Using and Abusing the Singleton Pattern 220

They Are Really Just Global Variables, Right? 220

Just How Many of These Singletons Do You Have? 221

Singletons on a Need-to-Know Basis 221

Curing the Testing Blues 223

Singletons in the Wild 224

Wrapping Up 225

Chapter 13: Picking the Right Class with a Factory 227

A Different Kind of Duck Typing 228

The Template Method Strikes Again 231

Parameterized Factory Methods 233

Classes Are Just Objects, Too 236

Bad News: Your Program Hits the Big Time 237

Bundles of Object Creation 239

Classes Are Just Objects (Again) 241

Leveraging the Name 242

Using and Abusing the Factory Patterns 244

Factory Patterns in the Wild 244

Wrapping Up 246

Chapter 14: Easier Object Construction with the Builder 249

Building Computers 250

Polymorphic Builders 253

Builders Can Ensure Sane Objects 256

Reusable Builders 257

Better Builders with Magic Methods 258

Using and Abusing the Builder Pattern 259

Builders in the Wild 259

Wrapping Up 260

Chapter 15: Assembling Your System with the Interpreter 263

The Right Language for the Job 264

Building an Interpreter 264

A File-Finding Interpreter 267

Finding All the Files 267

Finding Files by Name 268

Big Files and Writable Files 269

More Complex Searches with Not, And, and Or 270

Creating the AST 272

A Simple Parser 272

A Parser-less Interpreter? 274

Let XML or YAML Do the Parsing? 276

Racc for More Complex Parsers 277

Let Ruby Do the Parsing? 277

Using and Abusing the Interpreter Pattern 277

Interpreters in the Wild 278

Wrapping Up 279

PART III: Patterns for Ruby 281

Chapter 16: Opening Up Your System with Domain-Specific Languages 283

The Domain of Specific Languages 283

A File Backup DSL 284

It's a Data File--No, It's a Program! 285

Building PackRat 287

Pulling Our DSL Together 288

Taking Stock of PackRat 289

Improving PackRat 290

Using and Abusing Internal DSLs 293

Internal DSLs in the Wild 294

Wrapping Up 295

Chapter 17: Creating Custom Objects with Meta-programming 297

Custom-Tailored Objects, Method by Method 298

Custom Objects, Module by Module 300

Conjuring Up Brand-New Methods 301

An Object's Gaze Turns Inward 306

Using and Abusing Meta-programming 306

Meta-programming in the Wild 308

Wrapping Up 311

Chapter 18: Convention Over Configuration 313

A Good User Interface--for Developers 315

Anticipate Needs 315

Let Them Say It Once 316

Provide a Template 316

A Message Gateway 317

Picking an Adapter 319

Loading the Classes 320

Adding Some Security 323

Getting the User Started 325

Taking Stock of the Message Gateway 326

Using and Abusing the Convention Over Configuration Pattern 327

Convention Over Configuration in the Wild 328

Wrapping Up 328

Chapter 19: Conclusion 331

Appendix A: Getting Hold of Ruby 333

Appendix B: Digging Deeper 335

Index 339

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020