SlideShare a Scribd company logo
The black magic of
Ruby
metaprogramming
I am Cristian…
Gawyn

@cristianplanas
… and this is the story of
how I fell in love with
Ruby
It was 2011, when I read
this awesome book

(the smart part of this talk is based on it)
I was so excited that I
created my first gem just to
play with metaprogramming.
Easyregexp
http://github.com/Gawyn/easyregexp
Easyregexp
It was a regular expressions generator.
It relied heavily in metaprogramming.

It was never much useful.
Anyway, I felt like this
I mean, people who use
metaprogramming do have
superpowers.
They even know mysterious,
incomprehensible spells!
Repeat with me
The superclass of the eigenclass of an
object is the object’s class.
The superclass of the eigenclass of a
class is the eigenclass of the class’s
superclass.
Sorry, today we won’t talk
about eigenclasses.
We will focus on the most
down to earth part of
metaprogramming.
When I started using
metaprogramming in my
production code, I
remembered an old movie.
The Black Magic of Ruby Metaprogramming
In it, Mickey Mouse is the hard-working
apprentice of a powerful sorcerer.
One day, the sorcerer leaves,
and Mickey can play with
magic…
So let’s learn some tricks!
Monkey patching
Monkey patching
Adding code to an already defined
class.
An example

class String
def say_hello
p “hello”
end
end
“an string”. say_hello
=> “hello”
This means that we can
extend any class with our
own methods.
You can also redefine an
already existing method!
Dynamic methods
Dynamic methods
Define methods with an algorythm in
runtime.
A typical example

Imagine a class full of boring,
repeating methods.
A typical example
class User
ROLES = [“user”, “admin”]
# scopes for each role
scope :user, where(role: “user”)
scope :admin, where(role: “admin”)
# Identifying methods for each role
def user?
role == “user”
end

def admin?
role == “admin”
end
end
A typical example

Now let’s add some more roles:
ROLES = [“guest”, “user”,
“confirmed_user”, “moderator”,
“manager”, “admin”, “superadmin”]
Damn!
A typical example

Metaprogramming to the rescue!
A typical example
class User
ROLES = [“guest”, “user”, “confirmed_user”, “moderator”,
“manager”, “admin”, “superadmin”]
ROLES.each do |user_role|
scope user_role.to_sym, where(role: user_role)
define_method “#{user_role}?” do
role == user_role
end
end
end
Great!
Evaluating strings
as code
It does just that: run a string as if it was
code.
class_eval and instance_eval do the
same, just changing the context.
We can also use it on an object using
send.
An example

class Movie
attr_reader :title_en, :title_es, :title_it, :title_pt
def title
send(“title_#{I18n.locale}”)
end
end
An example
class Movie
translate :title, :overview
def translate(*attributes)
attributes.each do |attr|
define_method attr do
send(“#{attr}_#{I18n.locale}”)
end
end
end
end
You can even define
new methods like this!

String.class_eval(“def say_hello; puts „hello‟; end”)
“a string”.say_hello
#=> “hello”
method_missing
method_missing
It’s the method that gets executed
when the called method it’s not found.
We can monkey patch it!
An example
class MetalDetector
def method_missing(method, *args, &block)
if method =~ /metal/
puts “Metal detected!”
else
super
end
end
end
metal_detector = MetalDetector.new
metal_detector.bringing_some_metal_with_me
# => “Metal detected!”
A pretty exemplary use of
method_missing use are
Rails’ dynamic finders
(deprecated in Rails 4)
Calling finding methods with any
combination of attributes will work.

User.find_by_name_and_surname(“Mickey”, “Mouse”)
User.find_by_surname_and_movie(“Mouse”, “Fantasia”)
User.find_by_movie_and_job_and_name(“Fantasia”, “sorcerer”, “Mickey”)
So metaprogramming is
pretty cool, isn’t it?
It can get cooler
Let’s check how
ActiveRecord defines its
setter methods
(in an abbreviated version)
Defining setters
def method_missing(method, *args, &block)
unless self.class.attribute_methods_generated?
self.class.define_attribute_methods
if respond_to_without_attributes?(method)
send(method, *args, &block)
else
super
end
else

super
end
end
Finally it gets to something like this:
def define_write_method(attr_name)
method_definition = “def #{attr_name}=(new_value);
write_attribute(„#{attr_name}‟, new_value); end”
class_eval(method_definition, __FILE__, __LINE)
end

(as told, it’s a pretty abbreviated version)
To know more
Episode 8 of Metaprogramming Ruby: Inside ActiveRecord
https://github.com/rails/rails/blob/master/activerecord/lib/active_r
ecord/attribute_methods.rb

https://github.com/rails/rails/blob/master/activemodel/lib/active_
model/attribute_methods.rb
https://github.com/rails/rails/blob/master/activerecord/lib/active_r
ecord/attribute_methods/write.rb
But in the end of the movie, all the
magic backslashes…
Metaprogramming has its dangers
Unexpected
method override
It happens when you rewrite an
existing method changing its behavior
without checking the consequences.
That means all the code that rely in the
old method behavior will fail.
class Fixnum
alias :old_minus :alias :- :+
alias :+ :old_minus
end

4+3
#=> 1
5–2
#=> 7
Dynamic methods like the ones of the
example can also accidentally monkey
patch critical methods!
Code injection
through evaluation
If you use any kind of eval, remember to
think in all possible cases, specially if
users are involved.
You don’t want to evaluate
“User.destroy_all” on your own
application!
Even if users should be able to evaluate
code in your server, there are ways to
protect you:

Clean Rooms
Ghost methods
Methods working from inside
method_missing don’t “really” exist for
Ruby.
class MetalDetector
def method_missing(method, *args)
if method =~ /metal/
puts “Metal detected!”
else
super
end
end
end
metal_detector = MetalDetector.new
metal_detector.metal
# => “Metal detected!”

metal_detector.respond_to?(:metal)
#=> false
There is a work-around: to monkey
patch the respond_to? method.
Feels kinda hacky.
And still, it can be hard to maintain.
If you want to know more about the dangers of
method_missing, Paolo Perrotta (the author of
Metaprogramming Ruby) has a full presentation
about it: The revenge of method_missing()
Some final
thoughts
1. I look pretty cool with Superman trunks.
2. Metaprogramming is a name
for different techniques: you
can use some and avoid others.
Personally, I use plenty of
dynamic methods and avoid
method_missing.
3. Just be sure of what you do
when you use it.
The sorcerer won’t come to save you!
Thanks!

More Related Content

Viewers also liked (16)

PPT
Witch Hunts
drloewen
 
PPTX
The lapith and centaur metopes on the parthenon
Calum Rogers
 
PPT
THE LITTLE WITCH
goldenguapo
 
PDF
Designing Ruby APIs
Wen-Tien Chang
 
PPT
The Lucky 7 GameWorkshop Presentation
David Silverlight
 
PDF
Witch Kitchen
Emiliano Leon
 
PPTX
The Witch
RebeccaIH
 
KEY
MongoDB - Ruby document store that doesn't rhyme with ouch
Wynn Netherland
 
PPTX
Black Magic & Fake Pir in Pakistan.
diaryinc
 
PDF
HTML Lecture Part 1 of 2
Sharon Wasden
 
PPTX
Ruby object model
Chamnap Chhorn
 
PPT
Salem witch trials
SaraBates
 
PPTX
Superstition
Rita Vishwakarma
 
PPT
The Black Cat Intro
tranceking
 
PPTX
Black magic
Muhammad Hamza
 
PPT
Black magic presentation
Zarnigar Altaf
 
Witch Hunts
drloewen
 
The lapith and centaur metopes on the parthenon
Calum Rogers
 
THE LITTLE WITCH
goldenguapo
 
Designing Ruby APIs
Wen-Tien Chang
 
The Lucky 7 GameWorkshop Presentation
David Silverlight
 
Witch Kitchen
Emiliano Leon
 
The Witch
RebeccaIH
 
MongoDB - Ruby document store that doesn't rhyme with ouch
Wynn Netherland
 
Black Magic & Fake Pir in Pakistan.
diaryinc
 
HTML Lecture Part 1 of 2
Sharon Wasden
 
Ruby object model
Chamnap Chhorn
 
Salem witch trials
SaraBates
 
Superstition
Rita Vishwakarma
 
The Black Cat Intro
tranceking
 
Black magic
Muhammad Hamza
 
Black magic presentation
Zarnigar Altaf
 

Similar to The Black Magic of Ruby Metaprogramming (20)

PDF
Ruby Metaprogramming - OSCON 2008
Brian Sam-Bodden
 
PDF
Metaprogramming in Ruby
Nicolò Calcavecchia
 
PDF
Metaprogramming ruby
GeekNightHyderabad
 
KEY
Ruby
Kerry Buckley
 
PPTX
Metaprogramming in Ruby
Volodymyr Byno
 
PDF
Ruby basics
Aditya Tiwari
 
PPTX
Day 1 - Intro to Ruby
Barry Jones
 
PDF
Ruby seen from a C# developer
Codemotion
 
PDF
Ruby seen by a C# developer
Emanuele DelBono
 
KEY
Ruby's metaclass
xds2000
 
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
Henry S
 
PPT
Ruby Metaprogramming
Wei Jen Lu
 
PDF
Ruby — An introduction
Gonçalo Silva
 
PDF
Ruby Metaprogramming 08
Brian Sam-Bodden
 
PPT
Ruby for C# Developers
Cory Foy
 
PDF
Ruby and rails - Advanced Training (Cybage)
Gautam Rege
 
PDF
Less-Dumb Fuzzing and Ruby Metaprogramming
Nephi Johnson
 
PDF
Workin On The Rails Road
RubyOnRails_dude
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
PDF
RubyMiniGuide-v1.0_0
tutorialsruby
 
Ruby Metaprogramming - OSCON 2008
Brian Sam-Bodden
 
Metaprogramming in Ruby
Nicolò Calcavecchia
 
Metaprogramming ruby
GeekNightHyderabad
 
Metaprogramming in Ruby
Volodymyr Byno
 
Ruby basics
Aditya Tiwari
 
Day 1 - Intro to Ruby
Barry Jones
 
Ruby seen from a C# developer
Codemotion
 
Ruby seen by a C# developer
Emanuele DelBono
 
Ruby's metaclass
xds2000
 
Code for Startup MVP (Ruby on Rails) Session 2
Henry S
 
Ruby Metaprogramming
Wei Jen Lu
 
Ruby — An introduction
Gonçalo Silva
 
Ruby Metaprogramming 08
Brian Sam-Bodden
 
Ruby for C# Developers
Cory Foy
 
Ruby and rails - Advanced Training (Cybage)
Gautam Rege
 
Less-Dumb Fuzzing and Ruby Metaprogramming
Nephi Johnson
 
Workin On The Rails Road
RubyOnRails_dude
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
tutorialsruby
 
Ad

More from itnig (20)

PDF
Presentation of the project "Startups Made in Spain" · On Friday, January 9 a...
itnig
 
PDF
Web Scraping for Non Programmers
itnig
 
PDF
Hands-On Prototyping Without Code
itnig
 
PDF
Essentials Every Non-Technical Person Need To Know To Build The Best Tech-Tea...
itnig
 
PPTX
Die Another Day: Scaling from 0 to 4 million daily requests as a lone develop...
itnig
 
PDF
Data Tools cosystem_for_non_programmers
itnig
 
PDF
Futurology For Entrepreneurs: 7 Ways To Spot The Opportunities Of Tomorrow
itnig
 
PDF
Visualizing large datasets (BIG DATA itnig friday)
itnig
 
PDF
Make your own Open Source transition with CocoaPods
itnig
 
PDF
"El boom del Consumo Colaborativo" by Albert Cañigueral
itnig
 
PDF
Control Your Life - The Startup Way
itnig
 
PDF
Analítica Ágil - De la Sobrecarga a la Evidencia de los Datos
itnig
 
PPT
Ser público en internet lo es todo.
itnig
 
PPTX
Performance marketingonline enterategratis_
itnig
 
PPTX
SEO para ecommerce by Alfonso Moure
itnig
 
PPTX
Hablar en Público by Marion Chevalier
itnig
 
PDF
Collecting metrics with Graphite and StatsD
itnig
 
PPTX
La burbuja publicitaria
itnig
 
PPTX
Analisis de las empresas del Ibex35
itnig
 
PDF
QR-Codes 101 - Convirtiendo la tinta en bits
itnig
 
Presentation of the project "Startups Made in Spain" · On Friday, January 9 a...
itnig
 
Web Scraping for Non Programmers
itnig
 
Hands-On Prototyping Without Code
itnig
 
Essentials Every Non-Technical Person Need To Know To Build The Best Tech-Tea...
itnig
 
Die Another Day: Scaling from 0 to 4 million daily requests as a lone develop...
itnig
 
Data Tools cosystem_for_non_programmers
itnig
 
Futurology For Entrepreneurs: 7 Ways To Spot The Opportunities Of Tomorrow
itnig
 
Visualizing large datasets (BIG DATA itnig friday)
itnig
 
Make your own Open Source transition with CocoaPods
itnig
 
"El boom del Consumo Colaborativo" by Albert Cañigueral
itnig
 
Control Your Life - The Startup Way
itnig
 
Analítica Ágil - De la Sobrecarga a la Evidencia de los Datos
itnig
 
Ser público en internet lo es todo.
itnig
 
Performance marketingonline enterategratis_
itnig
 
SEO para ecommerce by Alfonso Moure
itnig
 
Hablar en Público by Marion Chevalier
itnig
 
Collecting metrics with Graphite and StatsD
itnig
 
La burbuja publicitaria
itnig
 
Analisis de las empresas del Ibex35
itnig
 
QR-Codes 101 - Convirtiendo la tinta en bits
itnig
 
Ad

Recently uploaded (20)

PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
July Patch Tuesday
Ivanti
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
July Patch Tuesday
Ivanti
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 

The Black Magic of Ruby Metaprogramming