Presentation used for the OpenTechSchool Hackership (http://www.hackership.org/) introduction to Meta-Programming in Ruby mini-workshop.
Meta Programmingin Ruby
View Slide
whoamiAmir Friedman● Developer at DaWanda (we’re hiring!)● Vegetarian● [email protected]● @NewArtRiot● http://github.com/psychocandy
What is “Meta Programming”?
“Code that treats code as data”
“Anything thatwould blow themind of a Javadeveloper”
“Code that writes code”
“There is no such thing as MP,there’s just programming”
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
Some Basic Concepts● Method manipulation● Class definition● Module definition● Mixin
The Ruby Ancestors ChainLet’s open pry (irb)!> self.class.ancestors=> [Object, PP::ObjectMixin, Kernel, BasicObject]> class Greeting ; end> Greeting.ancestors=> ?> module Hello ; end...
Ancestors Chainclass Greetingif rand(2) == 0include Xelseinclude YendendWe redirect messages during runtime :)
1st Layer● “Monkey Patching” (class, kernel method)● attr_… (attr_accessor, _reader, etc.)● alias :new_name :old_name
2nd LayerIdoms:● method_missing(sym, args)● respond_to?● “around_alias” (keep reference to the original)
3rd Layer● class_eval● instance_eval● define_method● dynamic include/extend
Let’s take a look at Railsand RSpec> require ‘rails’