SlideShare a Scribd company logo
Metaprogramming Rails
@JustusEapen
What is “metaprogramming”?
Metaprogramming is fun.
(dangerous)
Metaprogramming is usually
introspective or generative.
Introspection is code that tells you about code.
Generation is code that writes code.
When is this useful?
Introspection is useful all of the times.
Where is this method defined?
What classes inherit from this class?
What classes does this class inherit
from?
What classes include this module or
concern?
method(:method_name).source_locat
ion
Class.descendants
Class.ancestors
Oh crap. How do I do this again?
# How to get all the classes that include a module
concern :MyDopeModule do
def self.dope_classes
Rails.application.eager_load! # why is this important?
ActiveRecord::Base.descendants.select do |c|
c.included_modules.include?(MyDopeModule)
end
end
end
QUIZ:
Why should you not do that in
production?
Generative Methods be like...
Generative Methods are useful sometimes
I need to create many similar methods
I need to call methods dynamically
I need to dynamically set variables
I need to write a gem...
define_method(:foo) { do_something(foo) }
send(:method)
instance_variable_set(‘@var’, value):
# Getters and setters for an array attribute
# given an activerecord model with an array attribute
(1..5).each do |i|
define_method("attr_#{i}=".to_sym) do |val|
array[i] = val
save
end
define_method("attr_#{i}".to_sym) { take_aways[n] }
end
# File activerecord/lib/active_record/scoping/named.rb, line 143
def scope(name, body, &block)
unless body.respond_to?(:call)
raise ArgumentError, "The scope body needs to be callable."
end
if dangerous_class_method?(name)
raise ArgumentError, "You tried to define a scope named "#{name}" " "on the
model "#{self.name}", but Active Record already defined " "a class method with
the same name."
end
valid_scope_name?(name)
extension = Module.new(&block) if block
…
end
# File activerecord/lib/active_record/scoping/named.rb, line 143
def scope(name, body, &block)
...
if body.respond_to?(:to_proc)
singleton_class.send(:define_method, name) do |*args|
scope = all.scoping { instance_exec(*args, &body) }
scope = scope.extending(extension) if extension
scope || all
end
else
singleton_class.send(:define_method, name) do |*args|
scope = all.scoping { body.call(*args) }
scope = scope.extending(extension) if extension
scope || all
end
end
end
ActiveRecord be like:
We can even get meta-meta
# To DRY on scoping by a virtual attribute on active record models
# Add this to a VirtualScopableConcern
def self.virtual_scope_by(*virtual_attrs)
virtual_attrs.each do |virtual_attr|
scope "by_#{virtual_attr}".to_sym, -> {
all.to_a.sort_by(&virtual_attr) }
end
end
virtual_scope_by [:virtual_attribute_1, :virtual_attribute_2]
QUIZ:
Why should you not do that in
production?
What else can I do with metaprogramming?
1. Write a DSL for markup
2. Modify classes on the fly
3. Make ridiculously long method calls
a. String.method(:new).call
4. Catch undefined methods
a. Method_missing
5. Binding.pry
6. Penetrate scopes (defy encapsulation)
7. What else?
Where can I learn more?
● Metaprogramming Ruby and Antipatterns in Rails by Eugene Wang
● Metaprogramming in Ruby: It's All About the Self by Yehuda Katz
● Metaprogramming Ruby (book) by Paolo Perrotta
● In IRB, write some code, run it.
Conclusions:
Recursion is the source of all power
and...
Danger can be fun!

More Related Content

What's hot

Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
Java2Blog
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
anshu_atri
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
Mutinda Boniface
 
2- Introduction to java II
2-  Introduction to java II2-  Introduction to java II
2- Introduction to java II
Ghadeer AlHasan
 
Learn To Code: Diving deep into java
Learn To Code: Diving deep into javaLearn To Code: Diving deep into java
Learn To Code: Diving deep into java
SadhanaParameswaran
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
java - oop's in depth journey
java - oop's in depth journeyjava - oop's in depth journey
java - oop's in depth journey
Sudharsan Selvaraj
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
Pritom Chaki
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
OUM SAOKOSAL
 
5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java
Ghadeer AlHasan
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
University of Potsdam
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)
Syed Umair
 
An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)
Khubaib Ahmad Kunjahi
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
Garuda Trainings
 
6 class and methods
6    class and methods6    class and methods
6 class and methodsTuan Ngo
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 

What's hot (20)

Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
2- Introduction to java II
2-  Introduction to java II2-  Introduction to java II
2- Introduction to java II
 
Learn To Code: Diving deep into java
Learn To Code: Diving deep into javaLearn To Code: Diving deep into java
Learn To Code: Diving deep into java
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
java - oop's in depth journey
java - oop's in depth journeyjava - oop's in depth journey
java - oop's in depth journey
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java5- Overriding and Abstraction In Java
5- Overriding and Abstraction In Java
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)
 
An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
 
6 class and methods
6    class and methods6    class and methods
6 class and methods
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 

Similar to Metaprogramming Rails

Only oop
Only oopOnly oop
Only oop
anitarooge
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
Viva file
Viva fileViva file
Viva file
anupamasingh87
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
SMIJava
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Application package
Application packageApplication package
Application packageJAYAARC
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
Ólafur Andri Ragnarsson
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101Nando Vieira
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
naeemcse
 

Similar to Metaprogramming Rails (20)

Only oop
Only oopOnly oop
Only oop
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Java notes
Java notesJava notes
Java notes
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Viva file
Viva fileViva file
Viva file
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Application package
Application packageApplication package
Application package
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 

Metaprogramming Rails

  • 3.
  • 6. Introspection is code that tells you about code.
  • 7. Generation is code that writes code.
  • 8. When is this useful?
  • 9. Introspection is useful all of the times. Where is this method defined? What classes inherit from this class? What classes does this class inherit from? What classes include this module or concern? method(:method_name).source_locat ion Class.descendants Class.ancestors Oh crap. How do I do this again?
  • 10. # How to get all the classes that include a module concern :MyDopeModule do def self.dope_classes Rails.application.eager_load! # why is this important? ActiveRecord::Base.descendants.select do |c| c.included_modules.include?(MyDopeModule) end end end
  • 11. QUIZ: Why should you not do that in production?
  • 13. Generative Methods are useful sometimes I need to create many similar methods I need to call methods dynamically I need to dynamically set variables I need to write a gem... define_method(:foo) { do_something(foo) } send(:method) instance_variable_set(‘@var’, value):
  • 14. # Getters and setters for an array attribute # given an activerecord model with an array attribute (1..5).each do |i| define_method("attr_#{i}=".to_sym) do |val| array[i] = val save end define_method("attr_#{i}".to_sym) { take_aways[n] } end
  • 15. # File activerecord/lib/active_record/scoping/named.rb, line 143 def scope(name, body, &block) unless body.respond_to?(:call) raise ArgumentError, "The scope body needs to be callable." end if dangerous_class_method?(name) raise ArgumentError, "You tried to define a scope named "#{name}" " "on the model "#{self.name}", but Active Record already defined " "a class method with the same name." end valid_scope_name?(name) extension = Module.new(&block) if block … end
  • 16. # File activerecord/lib/active_record/scoping/named.rb, line 143 def scope(name, body, &block) ... if body.respond_to?(:to_proc) singleton_class.send(:define_method, name) do |*args| scope = all.scoping { instance_exec(*args, &body) } scope = scope.extending(extension) if extension scope || all end else singleton_class.send(:define_method, name) do |*args| scope = all.scoping { body.call(*args) } scope = scope.extending(extension) if extension scope || all end end end
  • 18.
  • 19. We can even get meta-meta
  • 20. # To DRY on scoping by a virtual attribute on active record models # Add this to a VirtualScopableConcern def self.virtual_scope_by(*virtual_attrs) virtual_attrs.each do |virtual_attr| scope "by_#{virtual_attr}".to_sym, -> { all.to_a.sort_by(&virtual_attr) } end end virtual_scope_by [:virtual_attribute_1, :virtual_attribute_2]
  • 21. QUIZ: Why should you not do that in production?
  • 22. What else can I do with metaprogramming? 1. Write a DSL for markup 2. Modify classes on the fly 3. Make ridiculously long method calls a. String.method(:new).call 4. Catch undefined methods a. Method_missing 5. Binding.pry 6. Penetrate scopes (defy encapsulation) 7. What else?
  • 23. Where can I learn more? ● Metaprogramming Ruby and Antipatterns in Rails by Eugene Wang ● Metaprogramming in Ruby: It's All About the Self by Yehuda Katz ● Metaprogramming Ruby (book) by Paolo Perrotta ● In IRB, write some code, run it.
  • 24. Conclusions: Recursion is the source of all power and...