Slide 1

Slide 1 text

Meta Programming in Ruby

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

What is “Meta Programming”?

Slide 4

Slide 4 text

“Code that treats code as data”

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

“Code that writes code”

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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 ...

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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