1. Trang chủ
  2. » Công Nghệ Thông Tin

1941222129 {E532F6FC} metaprogramming ruby program like the ruby pros (2nd ed ) perrotta 2014 08 18

262 370 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 262
Dung lượng 14,68 MB

Nội dung

www.it-ebooks.info www.it-ebooks.info What Readers Are Saying About Metaprogramming Ruby This is the one book about Ruby that makes you go “So that’s how it works” over and over again, as concepts such as the object model, DSLs, and blocks fall into place with that satisfying “Click!” sound It’s a great guide to what happens under the hood of a language that seems to involve a kind of magic deep inside I highly recommend it ➤ Peter Bakhirev Lead software engineer, Gilt City The previous edition of Metaprogramming Ruby changed my life and my code, and helped me get my first programming job You would think there would be no way to improve on a book that good, but Paolo Perrotta has done it Learn to unlock the hidden potential of this beautiful language, and fall in love with Ruby again ➤ Richard Schneeman Programmer, Heroku For gem authors and application developers alike, this book lays down the foundation everyone needs to harness the full power of Ruby Paolo describes metaprogramming in a fun and approachable way for all skill levels The knowledge garnered from reading this book will help you write cleaner code and work more effectively with legacy codebases ➤ Paul Elliott Rocketeer, Hashrocket www.it-ebooks.info If you want to follow the path of Ruby metaprogramming mastery, then this book is the best companion you can think of, no matter what your level is I had struggled with Ruby metaprogramming for years until I read this book; now it all makes sense ➤ Fabien Catteau Software developer, Tech-Angels This is a book that everyone who wants to have a deeper understanding of the inner workings of Ruby and Ruby on Rails should read The “spells” described in this book are invaluable tools to understand and use Ruby to its full extent This is not only about metaprogramming, but also about taking your Ruby programming to a different level ➤ Kosmas Chatzimichalis Software engineer I’m a huge Python fan, so I was supposed to disregard Ruby Paolo made me appreciate it Not only is Metaprogramming Ruby the book that allowed me to wrap my head around this esoteric and fascinating topic, but it also made me rethink the way I write code in other languages ➤ Arialdo Martini Programmer, JobRapido.com www.it-ebooks.info This book uncovers all the ins and outs of the art of metaprogramming in Ruby, with a no-nonsense approach and an irony that transpires from vibrant prose, never boring, without compromising any of its insightfulness Metaprogramming Ruby is one of those books that any serious Rubyist (and even the pros) will want to revisit from time to time ➤ Piergiuliano Bossi Principal engineer lead, Points Metaprogramming Ruby has been a hugely influential book for me, especially during a time when I wanted to learn about the inner workings of Ruby Paolo “Nusco” Perrotta made what is normally a complex topic fun, enjoyable, and very approachable ➤ Josh Kalderimis CEO, Travis CI www.it-ebooks.info Metaprogramming Ruby Program Like the Ruby Pros Paolo Perrotta The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina www.it-ebooks.info 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, PragProg 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://pragprog.com The team that produced this book includes: Lynn Beighley (editor) Potomac Indexing, LLC (indexer) Cathleen Small (copyeditor) Dave Thomas (typesetter) Janet Furlow (producer) Ellie Callahan (support) For international rights, please contact rights@pragprog.com Copyright © 2014 The Pragmatic Programmers, LLC All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted, 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-13: 978-1-94122-212-6 Encoded using the finest acid-free high-entropy binary digits Book version: P1.0—August 2014 www.it-ebooks.info I was thirteen, and I was tired of hanging out at the local toy shop to play Intellivision games I wanted my own videogame console I’d been bugging my parents for a while, with no success Then I found an alternative: I could play games on a computer as well So I asked my parents to buy me one of those new 8-bit computers—you know, to learn useful stuff My dad agreed, and my mom took me to the shop and bought me a Sinclair ZX Spectrum Mom, Dad… Here is something that I should’ve told you more often in my life: thank you This book is dedicated to the two of you I’m hoping it will make you proud, just like your once-kid is proud of you And while I’m here, I have something to confess about that life-changing day thirty years ago: I didn’t really want to learn stuff I just wanted to play In fact, that’s what I’ve been doing all these years www.it-ebooks.info Contents Foreword Acknowledgments Introduction xiii xv xvii Part I — Metaprogramming Ruby The M Word Ghost Towns and Marketplaces The Story of Bob, Metaprogrammer Metaprogramming and Ruby Monday: The Object Model Open Classes Inside the Object Model Quiz: Missing Lines What Happens When You Call a Method? Quiz: Tangle of Modules Wrap-Up 11 11 16 26 27 39 42 Tuesday: Methods A Duplication Problem Dynamic Methods method_missing Quiz: Bug Hunt Blank Slates Wrap-Up 45 46 48 55 64 66 69 Wednesday: Blocks The Day of the Blocks Quiz: Ruby# 73 73 75 www.it-ebooks.info 3 Contents Blocks Are Closures instance_eval() Callable Objects Writing a Domain-Specific Language Quiz: A Better DSL Wrap-Up •x 77 85 88 96 98 103 Thursday: Class Definitions Class Definitions Demystified Quiz: Class Taboo Singleton Methods Singleton Classes Quiz: Module Trouble Method Wrappers Quiz: Broken Math Wrap-Up 105 106 112 113 118 129 131 136 137 Friday: Code That Writes Code Coding Your Way to the Weekend Kernel#eval Quiz: Checked Attributes (Step 1) Quiz: Checked Attributes (Step 2) Quiz: Checked Attributes (Step 3) Quiz: Checked Attributes (Step 4) Hook Methods Quiz: Checked Attributes (Step 5) Wrap-Up 139 139 141 150 153 154 156 157 160 162 Epilogue 163 Part II — Metaprogramming in Rails Preparing for a Rails Tour Ruby on Rails Installing Rails The Rails Source Code The Design of Active Record A Short Active Record Example How Active Record Is Put Together A Lesson Learned 167 168 168 168 171 171 172 176 www.it-ebooks.info Appendix Spell Book counter 3.times { down } counter • 242 # => 10 # => For more information, see page 84 Singleton Method Define a method on a single object obj = "abc" class "x" For more information, see page 114 String of Code Evaluate a string of Ruby code my_string_of_code = "1 + 1" eval(my_string_of_code) # => For more information, see page 141 Symbol To Proc Convert a symbol to a block that calls a single method [1, 2, 3, 4].map(&:even?) # => [false, true, false, true] For more information, see page 225 www.it-ebooks.info report erratum • discuss Index SYMBOLS & operator, blocks, 89, 225 :: notation, constant paths, 22 @ character, setups and variables, 99 @@ prefix, for class variables, 110 || operator, Nil Guards, 219, 238 -> (stabby lambda) operator, 89 {} characters, blocks, 74 A accessor methods, 7, 116, 200–212 accounting example, 46–48, 52–55, 60–64, 69 Action Pack library, 168 Active Model library, 173 Active Record library about, 7, 168 attribute methods, 199– 212 design, 171–178 movie database example, Validations module, 175, 179–197 Active Support library about, 168 alias_method_chain, 189–197 Autoload module, 173 Concern module, 179, 183– 188 methods_transplantable? method, 208–210 UnboundMethod example, 95 add_checked_attribute method development plan, 140 eval method, 141–157 quizzes, 150–157, 160 removing eval method, 153 alias keyword, 132 alias_method method, 132 alias_method_chain method, 189– 197 Aliases, Around, see Around Aliases allocate method, 19 alphanumeric label example, 12–16, 36 ancestors chain attribute methods, 202 includers, 186 method lookup, 29–33, 55, 121 method_missing method, 202 object model rules, 126 prepending, 30–32, 135, 195 print_to_screen example, 40 removing from, 95 singleton classes, 122– 123 ancestors method, 30 and operator, blocks, 89, 225 anonymous classes and constants, 113 Ant language, 228–229 ANTLR, 228 ap method, 33 www.it-ebooks.info append_features method, 183– 187 arguments arity, 93 blocks, 74 arity, 93 Around Aliases alias_method_chain method, 193 vs overriding, 159, 190 quiz, 137 respond_to? method, 202 spell book, 231 using, 132–135 Array class grep method, 17, 55 inheritance, 20 arrays array explorer, 146–148 grep method, 17, 55 inheritance, 20 replacing elements, 15 attr_accessor method Class Macros, 116–118 quizzes, 150–157 review, 128–129 attr_checked method vs add_checked_attribute, 151, 156 development plan, 140– 141 quizzes, 156, 160 review, 151 attr_reader method, 117 attr_writer method, 117 attribute methods, 199–212 AttributeMethodCache module, 209 AttributeMethods module, 202 Index attributes, see also attr_accessor method; attr_checked method attribute methods, 199– 212 self and, 220 singleton classes, 127– 129 syntax, 217 @attributes variable, 201 AttrNames module, 210 autoload method, 173 autoloading, 95, 173 awesome_print gem, 33 B bar operator, Nil Guards, 219, 238 Base class (Active Record) connections, 172 definition, 174 design, 172–178 respond_to? method, 202 Validations module, 175, 179–197 BasicObject class Blank Slates, 67, 103 hooks, 158 inheritance, 20 instance_eval method, 68, 85–88, 108, 127, 145, 223 method_missing method, 48, 55–71, 200–206 binding method, 143 Binding objects, 143–145 bindings attribute methods, 208– 210 Binding objects, 143–145 blocks and, 77, 89 instance_eval method, 85– 88 scope and, 78–84 UnboundMethod objects, 94 Blank Slates Clean Rooms, 88, 103 method_missing method, 66– 69 spell book, 231 block_given? method, 74 blocks, see also procs attaching bindings, 89 basics, 73–77 Clean Rooms, 87, 233 closures as, 77–84 converting to procs, 89, 100, 224, 242 instance_eval method, 85– 88 instance_exec method, 86 quizzes, 75–77 Self Yield, 222–224, 241 vs Strings of Code, 145– 150 validate method, 172 validated attributes, 141, 154–155 boilerplate methods, 45 Bookworm examples label refactoring, 12–16, 36 loan refactoring, 111 method wrappers, 131– 136 Namespaces, 25 renaming methods, 117 Singleton Methods, 113– 118 Boolean operators and values, Nil Guards, 219–222 braces, blocks, 74 broken math quiz, 136 Builder, Blank Slate example, 67–69 C C attr_accessor method, 150 compile/runtime time, domain-specific languages, 230 C#, nested visibility, 79 C++ compile/runtime time, templates, using keyword, 75–77 caching, UnboundMethod objects, 207–210 calculate_initial_value method, 221 call method, 94 callable objects, see blocks; lambdas; procs callers method, 134 Camping framework example, 218 Cantrell, Paul, 93 chain of ancestors, see ancestors chain chained inclusions, 181–183, 186 www.it-ebooks.info • 244 chains of calls, 223 checked attributes, see attr_checked method class [...]... limited only by your own, undoubtedly fertile, imagination Metaprogramming gives you the power to do all these things Let’s see how this book will help you learn about it About This Book Part I, Metaprogramming Ruby, is the core of the book Chapter 1, The M Word, on page 3, walks you through the basic idea behind metaprogramming The following chapters tell the story of a week in the life of a newly hired... fact, metaprogramming is so deeply entrenched in the Ruby language that it’s not even sharply separated from “regular” programming You can’t look at a Ruby program and say, “This part here is metaprogramming, while this other part is not.” In a sense, metaprogramming is a routine part of every Ruby programmer’s job Once you master it, you’ll be able to tap into the full power of the language There... of them, be aware that some of the examples in this book might not yet work on your interpreter Book Editions The first edition of this book focused on Ruby 1.8, which has since been deprecated I updated the text to reflect the new features in Ruby, especially the ones that have been introduced by Ruby 2.x The chapters in Part II use the Rails source code as a source of examples Rails has changed a... about the each method, then you know enough Ruby to follow the ensuing text If you thought about the for keyword, then you’re probably new to Ruby In the second case, you can still embark on this metaprogramming adventure—just take an introductory Ruby text along with you, or take the excellent interactive tutorial at the Try Ruby! site.4 Are you on board, then? Great! Let’s start 4 http://tryruby.org... very popular among Rubyists, so I’ll call them spells instead Even if there’s nothing magical about them, they do look like magic spells to Ruby newcomers You’ll find references to spells everywhere in the book I reference a spell with the convention Class Macro (11 7) or String of Code (14 1), for example The number in parentheses is the page where the spell receives a name If you need a quick reference... (5 7), and fonder of others, such as Dynamic Methods (5 1) Parts of the new text reflect these changes of heart Finally, this second edition is a general cleanup of the first edition’s text I updated many examples that were using gems and source code that have been forgotten or changed since the previous book; I added a few spells and removed a few others that don’t seem very relevant anymore; I toned... In fact, the original draft of this book included unit tests for all code examples In the end, I found that those tests distracted from the metaprogramming techniques that are the meat of the book, so the tests fell on the cutting-room floor This doesn’t mean you shouldn’t write tests for your own metaprogramming endeavors On those occasions where I did show test code in this book, I used the testunit... example of metaprogramming In fact, many people think about code generation when the “M” word comes up This particular brand of metaprogramming implies that you use a program to generate or otherwise manipulate a second, distinct program and then you run the second program After you run the code generator, you can actually read the generated code and (if you want to test your tolerance for pain) even modify... also what happens under the hood with C++ templates: the compiler turns your templates into a regular C++ program before compiling them, and then you run the compiled program In this book, I’ll stick to a different meaning of metaprogramming, focusing on code that manipulates itself at runtime You can think of this as dynamic metaprogramming to distinguish it from the static metaprogramming of code generators... useful only for building something as sophisticated as Active Record If you want to take the path to advanced Ruby coding, you’ll find metaprogramming at every step Even if you’re happy with the amount of Ruby you already know and use, you’re still likely to stumble on metaprogramming in www.it-ebooks.info report erratum • discuss Metaprogramming and Ruby •9 the source of popular frameworks, in your favorite ... www.it-ebooks.info Metaprogramming Ruby Program Like the Ruby Pros Paolo Perrotta The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina www.it-ebooks.info Many of the designations used by manufacturers... I, Metaprogramming Ruby, is the core of the book Chapter 1, The M Word, on page 3, walks you through the basic idea behind metaprogramming The following chapters tell the story of a week in the. .. to the Weekend Kernel#eval Quiz: Checked Attributes (Step 1) Quiz: Checked Attributes (Step 2) Quiz: Checked Attributes (Step 3) Quiz: Checked Attributes (Step 4) Hook Methods Quiz: Checked Attributes

Ngày đăng: 07/01/2017, 20:55

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN