Meta Programming in Ruby - Code Camp 2010

3,697 views
3,535 views

Published on

meta programming in ruby
code camp 2010
steven soroka

Published in: Technology
0 Comments
19 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,697
On SlideShare
0
From Embeds
0
Number of Embeds
38
Actions
Shares
0
Downloads
302
Comments
0
Likes
19
Embeds 0
No embeds

No notes for slide




  • And yes, the site is in Ruby on Rails.

  • ruby-lang dot org describes it as....
  • what does author say?

  • what does author say?

  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • 2. Scripting language, but don’t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
  • simplest thing that could possibly work
    No libraries to import, no main declaration, no instantiation of string classes
    This, is a thing of beauty.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • Lets just get an idea of the syntax.
    Notice I don’t have to declare the type of the car variable, it’s automatically assigned at runtime.
  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • This is all fine and dandy, but does Ruby matter? I’d argue that it’s important.
    If you can judge that by the number of Ruby implementations, then I’d say so.
    IronMonkey is Adobe VM
    HotRuby is Ruby interpreter implemented in JS
    IronRuby is Microsoft’s work towards Ruby.NET

  • The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
  • The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
  • The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
  • The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
  • The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
  • Here’s an example of the GUI you can make with the WxRuby toolkit from Ruby
  • Here’s the exact same library and code run on a Mac. Notice both are native to their own OS.
  • Let’s get familiar with Ruby.
    We’re going to cover a lot of topics really quickly, so keep up. :)












  • important @
    less important @@
    global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.

  • important @
    less important @@
    global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.

  • important @
    less important @@
    global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.

  • important @
    less important @@
    global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.

  • local variables


  • This is what a symbol looks like. you can think of it as a string, and it is similar, but it’s got a key difference which I’ll get in to.
    In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.

  • This is what a symbol looks like. you can think of it as a string, and it is similar, but it’s got a key difference which I’ll get in to.
    In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.

  • This is what a symbol looks like. you can think of it as a string, and it is similar, but it’s got a key difference which I’ll get in to.
    In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.

  • This is what a symbol looks like. you can think of it as a string, and it is similar, but it’s got a key difference which I’ll get in to.
    In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.



  • The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
  • The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
  • The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
  • The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys
  • curly braces represent a key-value hash, not a block of code ; the hash has keys and values
    ;; you can fetch the value for the keys

  • {1}{2}, for example...
  • {1}{2}, for example...



  • means: you can change or extend any class. Good practices are up to you
    OCP is ..
  • means: you can change or extend any class. Good practices are up to you
    OCP is ..
  • means: you can change or extend any class. Good practices are up to you
    OCP is ..
  • means: you can change or extend any class. Good practices are up to you
    OCP is ..
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • lets reopen the Float class, and maybe our app doesn’t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
    Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we’ve done here. This violates the OCP
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.
  • if we give the method a different name, it wont collide with the round function and break any existing code using it.


  • strings are objects.
  • integers are objects
  • integers are objects
  • integers are objects
  • integers are objects
  • integers are objects
  • integers are objects
  • integers are objects
  • integers are objects
  • floats are objects
  • floats are objects
  • floats are objects







  • shorthand
  • Arrays are objects. You can actually do some REALLY cool things with methods that array gives you by default, things you’d normally write iterators and custom code for, but before we touch on that, I want to cover a little bit more background on Ruby
  • Like Array, You don’t need to use Hash.new to create a new hash object in Ruby.
    Using the braces is enough to denote that a hash object should be created
  • This shows a very common idiom in Ruby; using a hash to imitate Keyword Parameters
  • In fact, you don’t even need to provide the braces, and Ruby still figures out that you are declaring a hash.
  • Regular Expressions are awesome. You should already be familiar with these as a programmer. If you’re not, you’re doing a lot of things the hard way. This is even more true in Ruby. Support for Regular expressions is built in, just like array and hash.
  • Once you have an expression, you can use it with the match operator
  • Once you have an expression, you can use it with the match operator
  • Once you have an expression, you can use it with the match operator
  • Handy with substitution
  • Handy with substitution






  • {1}, because of this, {2}, and {3}.
  • blocks with iteration
  • blocks with iteration
  • blocks with iteration
  • blocks with iteration
  • <=> is the comparison operator
  • <=> is the comparison operator
  • <=> is the comparison operator
  • <=> is the comparison operator
  • <=> is the comparison operator
  • A closure is a block of code that, when run, is executed within the scope it was defined (i.e. local variables are available to the block), even after the function has returned, and its local scope has been destroyed. the local variables remain in existence as part of the closure object. When nothing refers to the closure anymore, it's garbage collected, and the local variables go away.
  • A closure is a block of code that, when run, is executed within the scope it was defined (i.e. local variables are available to the block), even after the function has returned, and its local scope has been destroyed. the local variables remain in existence as part of the closure object. When nothing refers to the closure anymore, it's garbage collected, and the local variables go away.








  • Now that we know a little bit about blocks, lets go back to array and look at the map() method
    map iterates the items in the array and calls the block you supply for each item, returning a new array with the results
  • Now that we know a little bit about blocks, lets go back to array and look at the map() method
    map iterates the items in the array and calls the block you supply for each item, returning a new array with the results
  • inject is used for reduction. You reduce the items of an array down to a single value. in this example I’m using it for summation
  • inject is used for reduction. You reduce the items of an array down to a single value. in this example I’m using it for summation
  • inject is used for reduction. You reduce the items of an array down to a single value. in this example I’m using it for summation
  • inject is used for reduction. You reduce the items of an array down to a single value. in this example I’m using it for summation
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • we can use inject to easily add support for summation to the array class.
    Now every array natively supports .sum. Rails gives you sum and .avg for free
  • Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
  • Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
  • Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
  • Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.










  • I’m sure all of you recognize the pattern of creating getters and setters for a class. I have a Car class here on the right with a getter and setter for a color attribute. On the left is the rest of the class with getters and setters for engine, make, and model. lot of repetition. Ruby embraces meta programming, and sets the bar for how we need to re-think what we might otherwise blindly accept as just “the way our language works”. In this case, the attr_accessor method.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.
  • which shortens 33 lines of code down to three! But attr_accessor isn’t magic Ruby compiler logic, it’s just a method. We can take a look at what that method might look like. Don’t worry if this goes over your head, I’ll get in to each of the methods here after we see how they’re used.





  • introspection

  • this gives you access to variables the class author might not have exposed.
  • Every object responds to instance_variables. Here we ask the Gem class from rubygems what instance variables it has defined internally. After it responds, we can query it for the value stored in any of those instance variables as if we had direct access to them.
  • every object responds to the .constants method. We can ask the Math module what constants it has defined. We can test them directly and see that they are in fact defined, and their values, but we can also request them by string, programatically. We can also set constants programmatically, as well as ask the class or module if they are defined, and even more weirdness with const_missing

  • inspect sums up my look at introspection. Every object in ruby responds to inspect with a string that describes the data the object holds, which, among other things, is handy for debugging









  • You’ve already seen define_method, it’s what made attr_accessor work.

  • but what happens when we want to implement div, span, anchors, unordered lists, etc?
  • First lets define a constant to hold all our tag types
  • There’s a really handy syntax for writing arrays of strings with a single word each, it’s %w()
  • before we go on, I’m going to switch the syntax I’m using to define class methods. instead of self.method_name I’m using this class << self pattern which is going to help keep things clean.
  • now instead of defining the strong method ourselves, lets change that to iterate the TAG_TYPES array and define each method.
  • Now we have all these methods defined for free. If we later add support for list items, we don’t have to add a method for it, we just add it to the TAG_TYPES array and the class automatically knows how to handle this.
  • Another way you can do this is with method_missing. Don’t even define the methods, just respond when they’re called.
  • In fact, why even have a list of supported tags at all? Now there’s nothing to change to support new tags
  • You get really cool code. What does this remind you of? It’s starting to look more and more like we created something that can generate XML for us. And in fact, that’s exactly the premise behind the Builder gem package authored by Jim Weirich.
  • But there’s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and “methods”, and any class you define must descend from Object. Clearly, we need more magic.
  • But there’s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and “methods”, and any class you define must descend from Object. Clearly, we need more magic.
  • But there’s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and “methods”, and any class you define must descend from Object. Clearly, we need more magic.
  • Meet undef_method. Care to take a guess what this does?
  • Now, you might expect Html.methods to return an empty array now, *click*
  • buuut, we undefined it. *pause* So there’s no more dot-methods method in our class.
    Practically speaking, there’s a couple methods you don’t want to undefine, but lets just gloss over that.
  • With Builder you create a new builder object, in this example it’s called ‘xml’. the methods you call on it become your tags. Blocks automatically nest tags within other tags.
  • And your output looks awesome. Life. is. good.
  • No, I’m not talking about restricting instantiation of a class to a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
  • A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don’t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.

  • eval - evaluates code, typically
    class_eval - evaluates code in the context of the object’s class, or metaclass
    instance_eval - evals code in the context of the object,
    module_eval - evals in context of a module
  • One day a specific client said to me, “These records should never get destroyed, ever. I want something in place to prevent them from being destroyed”. So, mixing the use of module_eval and the concept of creating a DSL, I came up with this patch. I reopen the ActiveRecord::Associations::ClassMethods module, which is part of Rails, and I define a class method called refuse_to_destroy!.
  • Now I have a DSL I can write in my models that tells it how to act. User.destroy now raises an exception
  • it works by evaluating the code in the User class and adds a before_destory hook on the ActiveRecord model.
  • I had this idiom in another language I came from, that essentially lets you temporarily change the scope. But when I came to Ruby, it just didn’t exist.
  • But it turns out you can achieve something similar with instance_eval, since it changes the scope while the block executes. Cool, but it doesn’t read as nice as that “with” command in my old language. But this is ruby, and you can make anything work the way you want it to!
  • We can add a with method to the Object class, which makes it available everywhere. We’ll set it up to take an object and a block of code as parameters, then call instance_eval on the object to change the scope to that object, and pass the block along to instance_eval, which will execute it in the object’s scope.
  • Now I have the syntax and method I was familiar with from the old language, implemented in Ruby. The great thing about this is there really is not a lot of limits on what you can do. You could almost create your own programming language or script, and execute it as if it’s ruby code using instance_eval
  • There’s already some really cool projects that take advantage of this. Cucumber actually executes english text as if it’s code


  • really common in Ruby
  • railsy

  • almost all operators in ruby... are methods!
  • almost all operators in ruby... are methods!
  • almost all operators in ruby... are methods!
  • almost all operators in ruby... are methods!

  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
  • My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).






  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • duck typing, looks like a duck, quacks like a duck, we don’t care.
    ppl objects are interacting with our bmw differently
  • lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
    the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn’t really that fast either, but lets call it negligible.
  • lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
    the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn’t really that fast either, but lets call it negligible.
  • lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
    the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn’t really that fast either, but lets call it negligible.
  • lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
    the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn’t really that fast either, but lets call it negligible.
  • lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
    the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn’t really that fast either, but lets call it negligible.
  • There are other ways to solve this problem, like making user count an instance variable and using the “or equals” meme (meam) you see here, which only evaluates the code on the right and sets user count if user count is nil or false. But lets ignore that, too.
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn’t drop out of scope and get freed
  • after the first time the method runs, it redefines itself to something like this. The method has both rewritten itself and accomplished a form of caching at the same time.
    self-optimization-code similar to this is used by Rails internally for routing. The first time the method is called it generates its own routing methods based on a more complete picture of what’s required and cuts out a lot of dead cycles that would otherwise check routes that are never used.





  • If you’re liking the Ruby vibe and you want to get in to it a little more, you’ll want to make a note to visit some of these sites.
  • Ruby screencasts



  • Meta Programming in Ruby - Code Camp 2010

    1. 1. Meta Programming in Ruby Steven Soroka @ssoroka
    2. 2. self.inspect
    3. 3. self.inspect •@ssoroka on twitter
    4. 4. self.inspect •@ssoroka on twitter • github.com/ssoroka
    5. 5. self.inspect •@ssoroka on twitter • github.com/ssoroka • blog.stevensoroka.ca
    6. 6. self.inspect • Professionally writing software for 12 years • Ruby for 3+ years • Taught Ruby on Rails at RRC • My biggest site has over 1 million users
    7. 7. What is Ruby? A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. http://www.ruby-lang.org
    8. 8. What is Ruby? - Yukihiro Matsumoto
    9. 9. What is Ruby? “Ruby is simple in appearance, but is very complex inside” - Yukihiro Matsumoto
    10. 10. What is Ruby? “Ruby is simple in appearance, but is very complex inside” “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python” - Yukihiro Matsumoto
    11. 11. What is Ruby?
    12. 12. What is Ruby? • Ruby is not Ruby on Rails
    13. 13. What is Ruby? • Ruby is not Ruby on Rails • Ruby is an interpreted language
    14. 14. What is Ruby? • Ruby is not Ruby on Rails • Ruby is an interpreted language • script language
    15. 15. What is Ruby? • Ruby is not Ruby on Rails • Ruby is an interpreted language • script language • terse
    16. 16. What is Ruby? • Ruby is not Ruby on Rails • Ruby is an interpreted language • script language • terse • completely Object Oriented
    17. 17. What is Ruby? • Ruby is not Ruby on Rails • Ruby is an interpreted language • script language • terse • completely Object Oriented • Free, really free.
    18. 18. puts “Hello World”
    19. 19. class Car
    20. 20. class Car def start
    21. 21. class Car def start puts "vroom vroom"
    22. 22. class Car def start puts "vroom vroom" end
    23. 23. class Car def start puts "vroom vroom" end end
    24. 24. class Car def start puts "vroom vroom" end end car = Car.new
    25. 25. class Car def start puts "vroom vroom" end end car = Car.new car.start # vroom vroom
    26. 26. Does Ruby matter?
    27. 27. Does Ruby matter? Rubinious MacRuby JRuby Ruby 1.8 IronRuby Cardinal HotRuby IronMonkey Ruby 1.9 Ruby Enterprise Edition
    28. 28. What Can I do with Ruby?
    29. 29. What Can I do with Ruby? • Cross-platform GUI apps (WxRuby, FXRuby, Ruby-GNOME2, Ruby Tk)
    30. 30. What Can I do with Ruby? • Cross-platform GUI apps (WxRuby, FXRuby, Ruby-GNOME2, Ruby Tk) • Mac Desktop apps with MacRuby and Cocoa
    31. 31. What Can I do with Ruby? • Cross-platform GUI apps (WxRuby, FXRuby, Ruby-GNOME2, Ruby Tk) • Mac Desktop apps with MacRuby and Cocoa • Web Apps (Ruby on Rails, Sinatra)
    32. 32. What Can I do with Ruby? • Cross-platform GUI apps (WxRuby, FXRuby, Ruby-GNOME2, Ruby Tk) • Mac Desktop apps with MacRuby and Cocoa • Web Apps (Ruby on Rails, Sinatra) • Replace Javascript?
    33. 33. What Can I do with Ruby? • Cross-platform GUI apps (WxRuby, FXRuby, Ruby-GNOME2, Ruby Tk) • Mac Desktop apps with MacRuby and Cocoa • Web Apps (Ruby on Rails, Sinatra) • Replace Javascript? • Soon Ruby.NET apps?
    34. 34. WxRuby GUI
    35. 35. WxRuby GUI
    36. 36. Introduction to Ruby New Concepts
    37. 37. Differences from C++
    38. 38. Differences from C++ • No type casting
    39. 39. Differences from C++ • No type casting • There’s only two container types: Array and Hash
    40. 40. Differences from C++ • No type casting • There’s only two container types: Array and Hash • There’s no type conversions, you’ll probably find that they aren’t necessary
    41. 41. Differences from C++ • No type casting • There’s only two container types: Array and Hash • There’s no type conversions, you’ll probably find that they aren’t necessary • Multithreading is built-in
    42. 42. Differences from C++
    43. 43. Differences from C++ • A unit testing lib comes standard with Ruby
    44. 44. Differences from C++ • A unit testing lib comes standard with Ruby • It’s self instead of this
    45. 45. Differences from C++ • A unit testing lib comes standard with Ruby • It’s self instead of this • Objects are strongly but dynamically typed. The runtime discovers at runtime if that method call actually works
    46. 46. Differences from Java
    47. 47. Differences from Java • There’s no static type checking.
    48. 48. Differences from Java • There’s no static type checking. • Variable names are just labels. They don’t have a type associated with them
    49. 49. Differences from Java • There’s no static type checking. • Variable names are just labels. They don’t have a type associated with them • There are no type declarations
    50. 50. Differences from Java • There’s no static type checking. • Variable names are just labels. They don’t have a type associated with them • There are no type declarations • foo = Foo.new(“hi”) instead of Foo foo = new Foo(“hi”)
    51. 51. Differences from Java • There’s no static type checking. • Variable names are just labels. They don’t have a type associated with them • There are no type declarations • foo = Foo.new(“hi”) instead of Foo foo = new Foo(“hi”)
    52. 52. Variables
    53. 53. Variables • Instance variables start with @
    54. 54. Variables • Instance variables start with @ • Class variables start with @@
    55. 55. Variables • Instance variables start with @ • Class variables start with @@ • Global variables start with $
    56. 56. Variables • Instance variables start with @ • Class variables start with @@ • Global variables start with $ • Any type of object can be stored in a given variable
    57. 57. a = 5.3 b = 15 a * b # 79.5
    58. 58. Truthiness • In Ruby, only false and nil are false • 0 is true • “” is true • [] is true
    59. 59. if 0 puts "0 is truthy" end # 0 is truthy
    60. 60. :recipient
    61. 61. deliver_report(:recipient => 'john@example.com') :recipient
    62. 62. Symbols
    63. 63. Symbols • Symbols are similar to strings, but are only allocated memory once, and are never freed.
    64. 64. Symbols • Symbols are similar to strings, but are only allocated memory once, and are never freed. • Great for keys, column names, and other strings that are repeated over and over again.
    65. 65. :name.object_id == :name.object_id
    66. 66. :name.object_id == :name.object_id # true
    67. 67. :name.object_id == :name.object_id # true “name”.object_id == “name”.object_id
    68. 68. :name.object_id == :name.object_id # true “name”.object_id == “name”.object_id # false
    69. 69. john = {
    70. 70. john = { :name => 'John Smith',
    71. 71. john = { :name => 'John Smith', :age => 42
    72. 72. john = { :name => 'John Smith', :age => 42 }
    73. 73. john = { :name => 'John Smith', :age => 42 } john[:name] # 'John Smith'
    74. 74. john = { :name => 'John Smith', :age => 42 } john[:name] # 'John Smith' john[:age] # 42
    75. 75. Interpolation • Double quoted strings are interpolated, single quoted strings are not. puts “five times three is #{5 * 3}” # five times three is 15 puts ‘five times three is #{5 * 3}’ # five times three is #{5 * 3}
    76. 76. Everything Has a Value
    77. 77. Everything Has a Value • Expressions and statements are the same thing in Ruby
    78. 78. Everything Has a Value • Expressions and statements are the same thing in Ruby • Everything returns a value, even if that value is nil
    79. 79. Implied Return Values
    80. 80. Implied Return Values if 3 > 2 5 end # returns 5
    81. 81. Implied Return Values
    82. 82. Implied Return Values if 2 > 21 5 end # returns nil
    83. 83. Implied Return Values
    84. 84. Implied Return Values pass = if 3.odd? ‘odd’ else ‘even’ end # pass == ‘odd’
    85. 85. Classes Are Open
    86. 86. Classes Are Open • Don’t violate Open/Close Principle
    87. 87. Classes Are Open • Don’t violate Open/Close Principle • OCP says classes should be...
    88. 88. Classes Are Open • Don’t violate Open/Close Principle • OCP says classes should be... • open for extension
    89. 89. Classes Are Open • Don’t violate Open/Close Principle • OCP says classes should be... • open for extension • closed for modification
    90. 90. Classes Are Open
    91. 91. Classes Are Open class Float
    92. 92. Classes Are Open class Float def round
    93. 93. Classes Are Open class Float def round floor
    94. 94. Classes Are Open class Float def round floor end
    95. 95. Classes Are Open class Float def round floor end end
    96. 96. Classes Are Open class Float def round floor end end 5.7.round
    97. 97. Classes Are Open class Float def round floor end end 5.7.round # 5
    98. 98. Classes Are Open
    99. 99. Classes Are Open class Float
    100. 100. Classes Are Open class Float def round_down
    101. 101. Classes Are Open class Float def round_down floor
    102. 102. Classes Are Open class Float def round_down floor end
    103. 103. Classes Are Open class Float def round_down floor end end
    104. 104. Classes Are Open class Float def round_down floor end end 5.7.round_down
    105. 105. Classes Are Open class Float def round_down floor end end 5.7.round_down # 5
    106. 106. Everything’s An Object
    107. 107. Everything’s An Object • properties are called attributes or instance variables
    108. 108. Everything’s An Object • properties are called attributes or instance variables • actions are called methods
    109. 109. String “I am a string” ‘I am a string’
    110. 110. Fixnum (Integers)
    111. 111. Fixnum (Integers) 42
    112. 112. Fixnum (Integers) 42 42.class # Fixnum
    113. 113. Fixnum (Integers) 42 42.class # Fixnum 42.methods
    114. 114. Fixnum (Integers) 42 42.class # Fixnum 42.methods # ["&", "*", "**", "+", "-", "/",
    115. 115. Fixnum (Integers) 42 42.class # Fixnum 42.methods # ["&", "*", "**", "+", "-", "/", "abs", "between?", "even?",
    116. 116. Fixnum (Integers) 42 42.class # Fixnum 42.methods # ["&", "*", "**", "+", "-", "/", "abs", "between?", "even?", "to_f", "zero?", "|", ...]
    117. 117. Fixnum (Integers) 42 42.class # Fixnum 42.methods # ["&", "*", "**", "+", "-", "/", "abs", "between?", "even?", "to_f", "zero?", "|", ...] 42.odd? # False
    118. 118. Fixnum (Integers) 42 42.class # Fixnum 42.methods # ["&", "*", "**", "+", "-", "/", "abs", "between?", "even?", "to_f", "zero?", "|", ...] 42.odd? # False 42.to_f # 42.0
    119. 119. Float
    120. 120. Float 42.0.class # Float
    121. 121. Float 42.0.class # Float 42.6.floor # 42
    122. 122. Float 42.0.class # Float 42.6.floor # 42 42.6.round # 43
    123. 123. Date (Rails)
    124. 124. Date (Rails) day = Date.today # Sat, 27 Feb 2010
    125. 125. Date (Rails) day = Date.today # Sat, 27 Feb 2010 day.tomorrow # Sun, 28 Feb 2010
    126. 126. Date (Rails) day = Date.today # Sat, 27 Feb 2010 day.tomorrow # Sun, 28 Feb 2010 day.year # 2010
    127. 127. Date (Rails) day = Date.today # Sat, 27 Feb 2010 day.tomorrow # Sun, 28 Feb 2010 day.year # 2010 day.leap? # false
    128. 128. Date (Rails) day = Date.today # Sat, 27 Feb 2010 day.tomorrow # Sun, 28 Feb 2010 day.year # 2010 day.leap? # false 42.days.ago # Sat, 16 Jan 2010
    129. 129. Array my_array = Array.new()
    130. 130. Array my_array = Array.new()
    131. 131. Array
    132. 132. Array my_array = []
    133. 133. Array
    134. 134. Array my_array = [1, 2, 3, 4, 5]
    135. 135. Hash email_settings = { :recipients => 'mom@mom.com', :subject => 'hi mom', :body => "I'm at CodeCamp!", :priority => :normal }
    136. 136. Hash email_settings = { :recipients => 'mom@mom.com', :subject => 'hi mom', :body => "I'm at CodeCamp!", :priority => :normal } send_email(email_settings)
    137. 137. Hash send_email({ :recipients => 'mom@mom.com', :subject => 'hi mom', :body => "I'm at Code Camp!", :priority => :normal })
    138. 138. Hash send_email( :recipients => 'mom@mom.com', :subject => 'hi mom', :body => "I'm at CodeCamp!", :priority => :normal )
    139. 139. Regular Expressions /[aeiou]/
    140. 140. Regular Expressions
    141. 141. Regular Expressions ‘scintillating!’ =~ /[aeiou]/
    142. 142. Regular Expressions ‘scintillating!’ =~ /[aeiou]/ #2
    143. 143. Regular Expressions ‘scintillating!’ =~ /[aeiou]/ #2
    144. 144. Regular Expressions
    145. 145. Regular Expressions ‘scintillating!’.gsub(/[aeiou]/, ‘*’)
    146. 146. Regular Expressions ‘scintillating!’.gsub(/[aeiou]/, ‘*’) # ‘sc*nt*ll*t*ng!’
    147. 147. Classes • Single inheritance only • but can include functionality from modules • can open a class at any time to add methods • ... are objects!
    148. 148. Methods • can end in ? or ! • “apples”.is_a?(String) • Are objects!
    149. 149. Operators are Methods
    150. 150. Operators are Methods • Most operators are methods
    151. 151. Operators are Methods • Most operators are methods • and can be redefined
    152. 152. Operators are Methods • Most operators are methods • and can be redefined class Fixnum def +(other) self - other end end
    153. 153. Operators are Methods • Most operators are methods • and can be redefined class Fixnum def +(other) self - other end end 5 + 3 # => 2
    154. 154. Blocks • In Ruby, a block is a namless function that can be stored as a callable object, called a Proc • Blocks can be stored in variables • Blocks can be passed to methods to customize their behavior
    155. 155. @users = User.find(:all)
    156. 156. @users = User.find(:all) @users.each { |user|
    157. 157. @users = User.find(:all) @users.each { |user| user.send_invoice!
    158. 158. @users = User.find(:all) @users.each { |user| user.send_invoice! }
    159. 159. arr = [5,3,1,5,3,2,6,8,1,2]
    160. 160. arr = [5,3,1,5,3,2,6,8,1,2] arr.sort{|a,b| a <=> b }
    161. 161. arr = [5,3,1,5,3,2,6,8,1,2] arr.sort{|a,b| a <=> b } # [1, 1, 2, 2, 3, 3, 5, 5, 6, 8]
    162. 162. arr = [5,3,1,5,3,2,6,8,1,2] arr.sort{|a,b| a <=> b } # [1, 1, 2, 2, 3, 3, 5, 5, 6, 8] arr.sort{|a,b| b <=> a }
    163. 163. arr = [5,3,1,5,3,2,6,8,1,2] arr.sort{|a,b| a <=> b } # [1, 1, 2, 2, 3, 3, 5, 5, 6, 8] arr.sort{|a,b| b <=> a } # [8, 6, 5, 5, 3, 3, 2, 2, 1, 1]
    164. 164. Block Objects are Closures
    165. 165. Block Objects are Closures • Block Objects (Procs) can be executed anywhere and can take their context (called binding) with them.
    166. 166. Block Objects are Closures • Block Objects (Procs) can be executed anywhere and can take their context (called binding) with them. • A closure is a block of code that, when run, is executed within the scope it was defined (i.e. local variables are available to the block), even after the function has returned, and its local scope has been destroyed.
    167. 167. user_total = Proc.new {
    168. 168. user_total = Proc.new { User.count
    169. 169. user_total = Proc.new { User.count }
    170. 170. user_total = Proc.new { User.count } user_total.call
    171. 171. user_total = Proc.new { User.count } user_total.call # 52
    172. 172. user_total = Proc.new { User.count } user_total.call # 52 # user is added
    173. 173. user_total = Proc.new { User.count } user_total.call # 52 # user is added user_total.call
    174. 174. user_total = Proc.new { User.count } user_total.call # 52 # user is added user_total.call # 53
    175. 175. Array#map
    176. 176. Array#map [1,2,3,4,5].map{|i| i * 2}
    177. 177. Array#map [1,2,3,4,5].map{|i| i * 2} # [2,4,6,8,10]
    178. 178. Array#inject
    179. 179. Array#inject [1,2,3,4,5].inject(0){|sum, i|
    180. 180. Array#inject [1,2,3,4,5].inject(0){|sum, i| i + sum
    181. 181. Array#inject [1,2,3,4,5].inject(0){|sum, i| i + sum }
    182. 182. Array#inject [1,2,3,4,5].inject(0){|sum, i| i + sum } # 15
    183. 183. Array#inject
    184. 184. Array#inject class Array
    185. 185. Array#inject class Array def sum
    186. 186. Array#inject class Array def sum self.inject(0){|sum, i| i + sum }
    187. 187. Array#inject class Array def sum self.inject(0){|sum, i| i + sum } end
    188. 188. Array#inject class Array def sum self.inject(0){|sum, i| i + sum } end end
    189. 189. Array#inject class Array def sum self.inject(0){|sum, i| i + sum } end end [1,2,3,4,5].sum
    190. 190. Array#inject class Array def sum self.inject(0){|sum, i| i + sum } end end [1,2,3,4,5].sum # 15
    191. 191. Array#inject
    192. 192. Array#inject [1,2,3,4,5].inject(0){|best, i|
    193. 193. Array#inject [1,2,3,4,5].inject(0){|best, i| i % 2 == 0 ? i : best
    194. 194. Array#inject [1,2,3,4,5].inject(0){|best, i| i % 2 == 0 ? i : best }
    195. 195. Array#inject [1,2,3,4,5].inject(0){|best, i| i % 2 == 0 ? i : best } #4
    196. 196. Array#select
    197. 197. Array#select [1,2,3,4,5].select{| i|
    198. 198. Array#select [1,2,3,4,5].select{| i| i % 2 == 0
    199. 199. Array#select [1,2,3,4,5].select{| i| i % 2 == 0 }
    200. 200. Array#select [1,2,3,4,5].select{| i| i % 2 == 0 } # [2, 4]
    201. 201. Array#reject
    202. 202. Array#reject [1,2,3,4,5].reject{| i|
    203. 203. Array#reject [1,2,3,4,5].reject{| i| i % 2 == 0
    204. 204. Array#reject [1,2,3,4,5].reject{| i| i % 2 == 0 }
    205. 205. Array#reject [1,2,3,4,5].reject{| i| i % 2 == 0 } # [1, 3, 5]
    206. 206. Extending Classes • Make a module • include it in to a class
    207. 207. Extending Classes • Make a module • include it in to a class module Awesomeness end class Mundane include Awesomeness end
    208. 208. Meta Programming Meta programming is writing code that writes code
    209. 209. class Car def color @color end def color=(color) @color = color end ...
    210. 210. class Car def color @color class Car end def color=(color) def color @color = color end @color def engine @engine end def engine=(engine) @engine = engine end end def make @make end def color=(color) def make=(make) @make = make end @color = color def model @model end end def model=(model) @model = model ... end end
    211. 211. class Car attr_accessor :color, :engine, :make, :model end
    212. 212. class Car attr_accessor :color, :engine, :make, :model end class Object
    213. 213. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes)
    214. 214. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute|
    215. 215. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter
    216. 216. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do
    217. 217. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}")
    218. 218. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end
    219. 219. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter
    220. 220. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter define_method("#{attribute}=") do |var|
    221. 221. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter define_method("#{attribute}=") do |var| instance_variable_set("@#{attribute}", var)
    222. 222. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter define_method("#{attribute}=") do |var| instance_variable_set("@#{attribute}", var) end
    223. 223. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter define_method("#{attribute}=") do |var| instance_variable_set("@#{attribute}", var) end }
    224. 224. class Car attr_accessor :color, :engine, :make, :model end class Object def self.attr_accessor(*attributes) attributes.each{|attribute| # define getter define_method(attribute) do instance_variable_get("@#{attribute}") end # define setter define_method("#{attribute}=") do |var| instance_variable_set("@#{attribute}", var) end } end
    225. 225. Introspection self.inspect
    226. 226. .class
    227. 227. .class • Any object will respond to .class
    228. 228. .class • Any object will respond to .class • Car.new.class # Car
    229. 229. .class • Any object will respond to .class • Car.new.class # Car • Car.class # Class
    230. 230. .ancestors • class BMW < Car ... end • BMW.ancestors # [Car, Object, Kernel]
    231. 231. .methods • Every object responds to .methods
    232. 232. .instance_variable_set • object.instance_variable_set(“@quantity”, 51)
    233. 233. .instance_variable_get • object.instance_variable_get(“@quantity”) # 25
    234. 234. .instance_variables • Gem.instance_variables # [“@gem_home”, “@ruby”, “@gem_path”, ...] • Gem.instance_variable_get( “@gem_home”) # [“/Library/Ruby/Gems/1.8”, ...]
    235. 235. .constants • Math.constants # [“PI”, “E”] • Math::PI # 3.14159265358979 • Math::E # 2.71828182845905 • Math.const_get(“PI”) # 3.14159265358979 • Math.const_set(“GOOGOL”, 10 ** 100)
    236. 236. .respond_to? • Tells you if objects will respond to a certain method. • ‘string’.respond_to?(:size) # true
    237. 237. .inspect • Car.new.inspect # => "#<Car:0x123d9e8>" • fish = :tuna fish.inspect # => ":tuna" • 5.inspect # => "5"
    238. 238. Dynamically Calling Methods • car.respond_to?(:start_engine) • car.send(:start_engine)
    239. 239. Method Missing • You can define ghost methods that don’t actually exist, but pretend to when requested
    240. 240. class Elephant def initialize @called = [] end def method_missing(method, *args, &block) @called << method end def talk puts @called.inspect end end
    241. 241. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end
    242. 242. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end suzie = Elephant.new
    243. 243. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end suzie = Elephant.new suzie.brush
    244. 244. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end suzie = Elephant.new suzie.brush suzie.do_tricks
    245. 245. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end suzie = Elephant.new suzie.brush suzie.do_tricks suzie.ride
    246. 246. class Elephant # ... def method_missing(method, *args, &block) @called << method end def talk # ... end suzie = Elephant.new suzie.brush suzie.do_tricks suzie.ride suzie.talk # [‘brush’, ‘do_tricks’, ‘ride’]
    247. 247. define_method() class Html def self.tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end end
    248. 248. class Html def self.tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end end Html.tag(‘strong’, “I’m strong!”) # <strong>I’m strong!</strong>
    249. 249. class Html def self.tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end def self.strong(content) tag(‘strong’, content) end end Html.strong(“I’m strong!”) # <strong>I’m strong!</strong>
    250. 250. class Html TAG_TYPES = [‘strong’, ‘div’, ‘span’, ‘a’, ‘ul’] def self.tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end def self.strong(content) tag(‘strong’, content) end end Html.strong(“I’m strong!”) # <strong>I’m strong!</strong>
    251. 251. class Html TAG_TYPES = %w(strong div span a ul) def self.tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end def self.strong(content) tag(‘strong’, content) end end Html.strong(“I’m strong!”) # <strong>I’m strong!</strong>
    252. 252. class Html TAG_TYPES = %w(strong div span a ul) class << self def tag(tag_name, content) "<#{tag_name}>#{content}</ #{tag_name}>" end def strong(content) tag(‘strong’, content) end end end
    253. 253. class Html TAG_TYPES = %w(strong div span a ul) class << self def tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end TAG_TYPES.each{|tag_type| define_method(tag_type) do |content| tag(tag_type, content) end } end end
    254. 254. Html.strong(‘buffalo’) # <strong>buffalo</strong> Html.span(‘distances’) # <span>distances</span> Html.a(‘revelation’) # <a>revelation</a>
    255. 255. class Html TAG_TYPES = %w(strong div span a ul) class << self def tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end def method_missing(method, *args) if TAG_TYPES.include?(method) tag(method, *args) else super end end end end
    256. 256. class Html class << self def tag(tag_name, content) "<#{tag_name}>#{content}</#{tag_name}>" end def method_missing(method, *args) tag(method, *args) end end end
    257. 257. Html.li(‘list item 1’) # <li>list item 1</li> Html.think(‘test’) # <think>test</think> Html.name(‘Steven Soroka’) # <name>Steven Soroka</name>
    258. 258. Object.methods.size # 75 (or more)
    259. 259. Object.methods.size # 75 (or more) Object.methods
    260. 260. Object.methods.size # 75 (or more) Object.methods # ["inspect", "private_class_method", "const_missing", ...]
    261. 261. undef_method() class Html class << self methods.each{|method| undef_method(method) } end end
    262. 262. undef_method() Html.methods # [] ?
    263. 263. undef_method() NoMethodError: undefined method `methods' for #<Class:0x408bc>
    264. 264. XML Builder xml.instruct! xml.html { xml.head { xml.title("History") } xml.body { xml.h1("Header") xml.p("paragraph") } }
    265. 265. XML Builder <?xml version="1.0" encoding="UTF-8"? > <html> <head> <title>History</title> </head> <body> <h1>Header</h1> <p>paragraph</p> </body> </html>
    266. 266. Singleton Methods •methods defined on a single instance of a class. •unrelated to class singletons
    267. 267. big_button = Button.new
    268. 268. big_button = Button.new little_button = Button.new
    269. 269. big_button = Button.new little_button = Button.new def big_button.click
    270. 270. big_button = Button.new little_button = Button.new def big_button.click do_big_stuff
    271. 271. big_button = Button.new little_button = Button.new def big_button.click do_big_stuff end
    272. 272. big_button = Button.new little_button = Button.new def big_button.click do_big_stuff end def little_button.click
    273. 273. big_button = Button.new little_button = Button.new def big_button.click do_big_stuff end def little_button.click act_important
    274. 274. big_button = Button.new little_button = Button.new def big_button.click do_big_stuff end def little_button.click act_important end
    275. 275. Domain-Specific Language (DSL)
    276. 276. eval • eval • class_eval • instance_eval • module_eval
    277. 277. module ActiveRecord class RecordCannotBeDestroyed < ActiveRecordError end module Associations module ClassMethods def refuse_to_destroy! module_eval %Q{ before_destroy do |record| raise RecordCannotBeDestroyed, "You cannot destroy #{record.class.name} records." unless record.new_record? end } end end end end
    278. 278. class User < ActiveRecord::Base refuse_to_destroy! end # @user.destroy now raises an exception
    279. 279. def refuse_to_destroy! module_eval %Q{ before_destroy do |record| raise RecordCannotBeDestroyed, "You cannot destroy #{record.class.name} records." unless record.new_record? end } end
    280. 280. car.start car.reverse car.wheel.turn car.gas_pedal.press car.brake_pedal.press with car do start reverse wheel.turn gas_pedal.press brake_pedal.press end
    281. 281. car.instance_eval { start reverse wheel.turn gas_pedal.press brake_pedal.press }
    282. 282. class Object def with(obj, &block) obj.instance_eval &block end end
    283. 283. with car do start reverse wheel.turn gas_pedal.press brake_pedal.press end
    284. 284. Aliasing Methods • basically copies a method with a new name • alias chaining • aka: alias method chaining
    285. 285. ['apple', 'lobster', 'fish', 'balloons'].include?('fish') # true ['apple', 'lobster', 'fish', 'balloons'].include?(/(lobster|fish)/) # false
    286. 286. class Array def include_with_regexp?(matcher) if matcher.is_a?(Regexp) any?{|i| i =~ matcher } else include_without_regexp?(matcher) end end alias :include_without_regexp? :include? alias :include? :include_with_regexp? end
    287. 287. class Array def include_with_regexp?(matcher) if matcher.is_a?(Regexp) any?{|i| i =~ matcher } else include_without_regexp?(matcher) end end alias_method_chain :include?, :regexp end
    288. 288. ['apple', 'lobster', 'fish', 'balloons'].include?( /(lobster|fish)/) # true
    289. 289. Operator Overloading
    290. 290. Operator Overloading class Fixnum def +(other) self - other end end
    291. 291. Operator Overloading class Fixnum def +(other) self - other end end 5 + 3 # => 2
    292. 292. Operator Overloading
    293. 293. Operator Overloading class Fixnum def +(other) (self.to_s + other.to_s).to_i end end
    294. 294. Operator Overloading class Fixnum def +(other) (self.to_s + other.to_s).to_i end end 5 + 3 # => 53
    295. 295. More Examples • Object Proxies • Code that rewrites itself • Optimization • Caching
    296. 296. Object Proxy
    297. 297. Object Proxy class SpyProxy
    298. 298. Object Proxy class SpyProxy def initialize(target)
    299. 299. Object Proxy class SpyProxy def initialize(target) @target = target
    300. 300. Object Proxy class SpyProxy def initialize(target) @target = target end
    301. 301. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args)
    302. 302. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args) puts “#{method} called with args:
    303. 303. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args) puts “#{method} called with args: #{args.inspect}”
    304. 304. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args) puts “#{method} called with args: #{args.inspect}” @target.send(method, *args)
    305. 305. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args) puts “#{method} called with args: #{args.inspect}” @target.send(method, *args) end
    306. 306. Object Proxy class SpyProxy def initialize(target) @target = target end def method_missing(method, *args) puts “#{method} called with args: #{args.inspect}” @target.send(method, *args) end end
    307. 307. Object Proxy
    308. 308. Object Proxy paul = Person.new
    309. 309. Object Proxy paul = Person.new steve = Person. new
    310. 310. Object Proxy paul = Person.new steve = Person. new bmw = BMW. new
    311. 311. Object Proxy paul = Person.new steve = Person. new bmw = BMW. new paul.start(bmw) # “clunk clunk”
    312. 312. Object Proxy paul = Person.new steve = Person. new bmw = BMW. new paul.start(bmw) # “clunk clunk” steve.start(bmw) # “vroom vroom”
    313. 313. Object Proxy paul = Person.new steve = Person. new bmw = BMW. new paul.start(bmw) # “clunk clunk” steve.start(bmw) # “vroom vroom” spy_bmw = SpyProxy.new(bmw)
    314. 314. Object Proxy
    315. 315. Object Proxy spy_bmw = SpyProxy.new(bmw)
    316. 316. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw)
    317. 317. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0]
    318. 318. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0] # turn_key called with args: []
    319. 319. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0] # turn_key called with args: [] # “vroom vroom”
    320. 320. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0] # turn_key called with args: [] # “vroom vroom” paul.start(spy_bmw)
    321. 321. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0] # turn_key called with args: [] # “vroom vroom” paul.start(spy_bmw) # turn_key called with args: []
    322. 322. Object Proxy spy_bmw = SpyProxy.new(bmw) steve.start(spy_bmw) # press_clutch called with args: [1.0] # turn_key called with args: [] # “vroom vroom” paul.start(spy_bmw) # turn_key called with args: [] # “clunk clunk”
    323. 323. Self-Optimization
    324. 324. Self-Optimization def get_random_user_id
    325. 325. Self-Optimization def get_random_user_id user_count = sql("select count(*) from users")
    326. 326. Self-Optimization def get_random_user_id user_count = sql("select count(*) from users") sql("select id from users
    327. 327. Self-Optimization def get_random_user_id user_count = sql("select count(*) from users") sql("select id from users offset #{rand(user_count)} limit 1")
    328. 328. Self-Optimization def get_random_user_id user_count = sql("select count(*) from users") sql("select id from users offset #{rand(user_count)} limit 1") end
    329. 329. Self-Optimization
    330. 330. Self-Optimization def get_random_user_id @user_count ||= sql("select count(*) from users") sql("select id from users offset #{rand(@user_count)} limit 1") end
    331. 331. Self-Optimization
    332. 332. Self-Optimization def get_random_user_id
    333. 333. Self-Optimization def get_random_user_id class_eval {
    334. 334. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users")
    335. 335. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do
    336. 336. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users
    337. 337. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users offset #{rand(user_count)} limit 1")
    338. 338. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users offset #{rand(user_count)} limit 1") end
    339. 339. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users offset #{rand(user_count)} limit 1") end }
    340. 340. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users offset #{rand(user_count)} limit 1") end } get_random_user_id
    341. 341. Self-Optimization def get_random_user_id class_eval { user_count = sql("select count(*) from users") define_method(‘get_random_user_id’) do sql("select id from users offset #{rand(user_count)} limit 1") end } get_random_user_id end
    342. 342. Self-Optimization
    343. 343. Self-Optimization def get_random_user_id sql("select id from users offset #{rand(1052023)} limit 1") end
    344. 344. Caching by rewriting methods?
    345. 345. Caching by rewriting methods? • You can rewrite a method as a form of caching
    346. 346. Caching by rewriting methods? • You can rewrite a method as a form of caching • Downside is cache invalidation becomes messy (doable, think alias)
    347. 347. Caching by rewriting methods? • You can rewrite a method as a form of caching • Downside is cache invalidation becomes messy (doable, think alias) • There’s easier ways
    348. 348. Caching by rewriting methods? • You can rewrite a method as a form of caching • Downside is cache invalidation becomes messy (doable, think alias) • There’s easier ways • @var ||= ...
    349. 349. Caching by rewriting methods? • You can rewrite a method as a form of caching • Downside is cache invalidation becomes messy (doable, think alias) • There’s easier ways • @var ||= ... • memoization (memoize in Rails)
    350. 350. Try Ruby in Your Browser http://TryRuby.org/ Download Ruby http://www.ruby-lang.org/en/downloads/
    351. 351. http://www.TeachMeToCode.com
    352. 352. Resources • http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html • http://www.ruby-lang.org/en/about • http://www.artima.com/intv/closures2.html • http://silverlight.net/learn/dynamic-languages/ • http://blog.headius.com/2008/04/promise-and-peril-for-alternative-ruby.html
    353. 353. Questions? @ssoroka - twitter
    354. 354. Merci @ssoroka - twitter

    ×