Lightning Talk on Metaprogramming in Ruby

9
Metaprogramming what’s up with that

Transcript of Lightning Talk on Metaprogramming in Ruby

Metaprogramming what’s up with that

Yo, Dawg - I heard you like programming so I got you some meta

so you can program your programs

Using Open Classes is Metaclass Integer def hearts self.times do print "\u2764 " end end end

irb(main):003:0> require "./meta.rb" => true irb(main):004:0> 3.hearts ❤ ❤ ❤ => 3 irb(main):005:0> 1.hearts ❤ => 1

Objects and Classes

Object stores only variables and a reference to the Class

Class stores only methods (both instance and class methods)

class = :Animal @says = “bark”

def speak puts @says end

A class is an object!

you can change variables on an object

you can change methods on a class

in ruby, you can do this whenever you want

if your code changes other code, especially when running, that’s metaprogramming

Text

Can be dangerous!But ruby 2.0 makes it safer

Refine is safer (ruby 2)module MadHacks refine Integer do def hearts self.times do print "\u2764 " end end end end !

irb(main):001:0> require "./meta.rb" => true irb(main):002:0> 1.hearts NoMethodError: undefined method `hearts' for 1:Fixnum from (irb):2 from /Users/mindlace/.rbenv/versions/2.0.0-p247/bin/irb:12:in `<main>' irb(main):003:0> using MadHacks => main irb(main):004:0> 1.hearts ❤ => 1

Lots of other techniques

Dynamic methods (add methods when they are named)

Method missing (respond to any method name)

And more!

Ruby makes it very easy to metaprogram

With power comes responsibility

Questions?