$30 off During Our Annual Pro Sale. View Details »

Ruby Meta-Programming for beginners

Ruby Meta-Programming for beginners

Presentation used for the OpenTechSchool Hackership (http://www.hackership.org/) introduction to Meta-Programming in Ruby mini-workshop.

Amir Friedman

December 03, 2013
Tweet

More Decks by Amir Friedman

Other Decks in Programming

Transcript

  1. Meta Programming
    in Ruby

    View Slide

  2. whoami
    Amir Friedman
    ● Developer at DaWanda (we’re hiring!)
    ● Vegetarian
    [email protected]
    ● @NewArtRiot
    ● http://github.com/psychocandy

    View Slide

  3. What is “Meta Programming”?

    View Slide

  4. “Code that treats code as data”

    View Slide

  5. “Anything that
    would blow the
    mind of a Java
    developer”

    View Slide

  6. “Code that writes code”

    View Slide

  7. “There is no such thing as MP,
    there’s just programming”

    View Slide

  8. What are we going to learn
    ● Clear uncertainty regarding MP
    ● Show different layers of MP
    ● Make you feel secure about MP
    ● Show examples from the real-world

    View Slide

  9. Some Basic Concepts
    ● Method manipulation
    ● Class definition
    ● Module definition
    ● Mixin

    View Slide

  10. The Ruby Ancestors Chain
    Let’s open pry (irb)!
    > self.class.ancestors
    => [Object, PP::ObjectMixin, Kernel, BasicObject]
    > class Greeting ; end
    > Greeting.ancestors
    => ?
    > module Hello ; end
    ...

    View Slide

  11. Ancestors Chain
    class Greeting
    if rand(2) == 0
    include X
    else
    include Y
    end
    end
    We redirect messages during runtime :)

    View Slide

  12. 1st Layer
    ● “Monkey Patching” (class, kernel method)
    ● attr_… (attr_accessor, _reader, etc.)
    ● alias :new_name :old_name

    View Slide

  13. 2nd Layer
    Idoms:
    ● method_missing(sym, args)
    ● respond_to?
    ● “around_alias” (keep reference to the original)

    View Slide

  14. 3rd Layer
    ● class_eval
    ● instance_eval
    ● define_method
    ● dynamic include/extend

    View Slide

  15. Let’s take a look at Rails
    and RSpec
    > require ‘rails’

    View Slide