SlideShare a Scribd company logo
1 of 31
Download to read offline
Metaprogramming
Ruby
Changing program constructs at runtime
– Suresh Pai
“Do you know that Ruby has class instance variables?”
Quick Intro to Ruby
• Inspired by Lisp, Smalltalk and Perl

• Interpreted (REPL)

• Object oriented (almost everything is an object)

• Dynamically and strongly typed

• Duck typing

• Optimized for programmer happiness
Code examples
• Interactive Ruby

• Logical operators and duck typing

• Methods

• Arrays & Hashes

• Code blocks and yield

• Classes, Objects

• Modules and Mixins
Code Samples - 001 to 004
What is metaprogramming?
• Manipulating language constructs at runtime

• Define classes on the fly

• Add methods to objects

• Wrap methods with custom before/after behavior 

• Create domain specific languages
PART 1
The Ruby object model
• Every value in Ruby is an object

• Ruby object is a structure that contains

• Some flags (frozen, tainted etc)

• Array of instance variables

• Reference to the class

• What is missing?
Code Samples - 005
Where are the methods?
• Methods exist only in classes, not objects

• The methods of an object are the instance methods of its class

• Ruby has methods for discovering methods including
Object#methods, Module#instance_methods

• Methods can be turned into objects using Object#method
Code Samples - 006
Blocks, Procs, Lambdas
• Blocks are just chunks of code between do … end or { .. }

• Methods can take a single block as an implicit parameter, and yield
control to the block

• Blocks can be turned into objects using 

• Proc.new

• lambda or ->

• The & operator

• Blocks are closures, they capture the surrounding scope

• Lambdas are closer to methods than Procs
Code Samples - 007
Classes
• Every object is an instance of some class

• Classes are objects too. A class is an instance of Class.

• The name of the class (i.e, String) is a constant that refers to
the Class object.

• The class keyword is a scope operator where 

• Inside you can write code that is executable

• self refers to the Class object

• Classes can be created dynamically with Class.new
Code Samples - 008
Inheritance
• All classes (except one) have exactly one superclass

• If not otherwise specified, the superclass is Object

• Object in turn inherits from BasicObject, which is the
object Ruby class that doesn’t have a superclass.

• A class’s superclass can be obtained with the superclass
method. 

• The entire chain of superclasses can be obtained with the
ancestors method.
Code Samples - 009
Method lookup
Right and Up Rule
Modules
• Modules are like classes, but different in a few ways

• Provide a scope for defining methods

• Modules are objects of class Module

• Cannot create new objects from modules 

• Modules do not participate in the inheritance hierarchy
directly, but can be included in the ancestors chain in
interesting ways.
include and prepend
• Both include and prepend insert the module into the
ancestors chain of the calling class (or module)

• include inserts directly above the caller

• prepend inserts directly below the caller

• This affects what super means when used in the methods
Code Samples - 009
Singleton Methods
• Ruby allows for defining methods on individual objects

• They are defined only on the object, not available for
others objects of the same class

• Class methods are a special case of the singleton
methods. They are actually singleton methods where the
object happens to be a class.
Code Samples - 010
Method lookup
Right and Up Rule
Singleton Classes
• Recall that methods live only in classes, not objects.

• Singleton methods cannot live in the object’s class, since
that is shared by all the other objects.

• Ruby creates a special singleton class for each object.
Also known as meta class, virtual class or eigen class.

• You can access it with singleton_class method or this
syntax class << object ; end
Code Samples - 011
Object#extend
• Including a module get the module’s instance methods,
not the singleton methods (class methods)

• So include the module in the singleton class

• Or equivalently; use extend

• extend module - make module’s instance methods also
be singleton methods
PART 2
Metaprogramming
Spells
Open Classes
• You can reopen any class and add methods to it

• You can reopen any module and add methods to it

• You can reopen any object and add methods to it

• A.K.A monkey patching

• Can use refinements to control the scope of changes
Code Samples - 012
method_missing
• If Ruby cannot find a method in the ancestors chain, it invokes
method_missing

• Classes can redefine method_missing to respond to messages
(“Ghost Methods”)

• Some downsides

• respond_to? Lies unless you also redefine
respond_to_missing?

• Ghost methods cannot be discovered with reflection

• However, can be very useful sometimes: https://github.com/
jimweirich/builder
define_method
• define_method is a singleton method defined in the
Module class

• Takes a string/symbol, and a block to create a named
instance method on the calling class

• Useful for defining families of related methods
Code Samples - 014
Scope Gates
• There are exactly three places where a program leaves the
previous scope behind and open a new one

• Class definitions

• Module definitions

• Methods

• Overcoming scope gates

• Flattening the scope

• Shared scope
Code Samples - 015
Writing a DSL
Code Samples - 016, 017
RedFlag is a monitor utility for the people in the sales department.

It should send the sales folks a message when an order is late, when total
sales are too low...basically, whenever one of many different things
happens. 

Sales wants to monitor dozens of different events, and the list is bound to
change every week or so.
The eval family of methods
Code Samples - 016, 017
• Kernel#eval can be used to evaluate any strings of code

• Module#class_eval - evaluates a block in the context of
an existing class

• BasicObject#instance_eval - evaluates a block in the
context of a specific object. Redefines self to be the
receiver

• class_exec and instance_exec can pass arguments to the
block
Hook methods
Code Samples - 018
• Object model is an eventful place and lots of things
happen there as your code runs like

• Classes are inherited

• Modules are mixed into classes (include, append)

• Methods are defined, undefined and removed
Code that writes code
Code Samples - 019
• Your boss wants a class macro attr_checked

• It should take the name of the attribute, as well as a block

• The block is used for validation

• If you assign a value to an attribute and the block doesn’t
turn true for that value, then you get an exception

• A class should gain access to attr_checked only when it
includes a CheckedAttributes module
Cons of Metaprogramming
• Learning curve for new developers

• Not easy to find symbols using grep

• Not easy to comprehend

• Needs more unit tests

• Need to be more careful when extending
– Zen Master Programmer
“There is no such thing as Metaprogramming.
It’s just programming all the way down.”

More Related Content

What's hot

An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
 
Java object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - BrainsmartlabsJava object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - Brainsmartlabsbrainsmartlabsedu
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed OverviewBuddha Tree
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentalsAnsgarMary
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective CAshiq Uz Zoha
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Hitesh-Java
 

What's hot (14)

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
Java object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - BrainsmartlabsJava object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - Brainsmartlabs
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentalsIntroduction to oop and java fundamentals
Introduction to oop and java fundamentals
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
Introduction to value types
Introduction to value typesIntroduction to value types
Introduction to value types
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 

Similar to Metaprogramming Ruby - Changing program constructs at runtime

Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyVolodymyr Byno
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingMH Abid
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSkillwise Group
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptBill Buchan
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 
12_oop templa.pptx
12_oop templa.pptx12_oop templa.pptx
12_oop templa.pptxRokaKaram
 
Code reviews
Code reviewsCode reviews
Code reviewsRoger Xia
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsRanel Padon
 
chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingWondimuBantihun1
 

Similar to Metaprogramming Ruby - Changing program constructs at runtime (20)

Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
inheritance
inheritanceinheritance
inheritance
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Java
JavaJava
Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
 
Javasession8
Javasession8Javasession8
Javasession8
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
12_oop templa.pptx
12_oop templa.pptx12_oop templa.pptx
12_oop templa.pptx
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programming
 

More from GeekNightHyderabad

Testing strategies in microservices
Testing strategies in microservicesTesting strategies in microservices
Testing strategies in microservicesGeekNightHyderabad
 
Scaling enterprise digital platforms with kubernetes
Scaling enterprise digital platforms with kubernetesScaling enterprise digital platforms with kubernetes
Scaling enterprise digital platforms with kubernetesGeekNightHyderabad
 
FreedomBox & Community Wi-Fi networks
FreedomBox & Community Wi-Fi networksFreedomBox & Community Wi-Fi networks
FreedomBox & Community Wi-Fi networksGeekNightHyderabad
 
Rendezvous with aucovei (autonomous connected car)
Rendezvous with aucovei (autonomous connected car)Rendezvous with aucovei (autonomous connected car)
Rendezvous with aucovei (autonomous connected car)GeekNightHyderabad
 
Role of AI & ML in beauty care industry
Role of AI & ML in beauty care industryRole of AI & ML in beauty care industry
Role of AI & ML in beauty care industryGeekNightHyderabad
 
Design lean agile_thinking presentation
Design lean agile_thinking presentationDesign lean agile_thinking presentation
Design lean agile_thinking presentationGeekNightHyderabad
 
Hardware hacking and internet of things
Hardware hacking and internet of thingsHardware hacking and internet of things
Hardware hacking and internet of thingsGeekNightHyderabad
 
Spring to Cloud - REST To Microservices
Spring to Cloud - REST To MicroservicesSpring to Cloud - REST To Microservices
Spring to Cloud - REST To MicroservicesGeekNightHyderabad
 
Building Cloud Native Applications Using Spring Boot and Spring Cloud
Building Cloud Native Applications Using Spring Boot and Spring CloudBuilding Cloud Native Applications Using Spring Boot and Spring Cloud
Building Cloud Native Applications Using Spring Boot and Spring CloudGeekNightHyderabad
 
Progressive Web Applications - The Next Gen Web Technologies
Progressive Web Applications - The Next Gen Web TechnologiesProgressive Web Applications - The Next Gen Web Technologies
Progressive Web Applications - The Next Gen Web TechnologiesGeekNightHyderabad
 
Scaling a Game Server: From 500 to 100,000 Users
Scaling a Game Server: From 500 to 100,000 UsersScaling a Game Server: From 500 to 100,000 Users
Scaling a Game Server: From 500 to 100,000 UsersGeekNightHyderabad
 
Big Data - Need of Converged Data Platform
Big Data - Need of Converged Data PlatformBig Data - Need of Converged Data Platform
Big Data - Need of Converged Data PlatformGeekNightHyderabad
 
Building a Data Lake - An App Dev's Perspective
Building a Data Lake - An App Dev's PerspectiveBuilding a Data Lake - An App Dev's Perspective
Building a Data Lake - An App Dev's PerspectiveGeekNightHyderabad
 
Understanding the Intelligent Cloud
Understanding the Intelligent CloudUnderstanding the Intelligent Cloud
Understanding the Intelligent CloudGeekNightHyderabad
 
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNightHyderabad
 

More from GeekNightHyderabad (20)

Testing strategies in microservices
Testing strategies in microservicesTesting strategies in microservices
Testing strategies in microservices
 
Scaling enterprise digital platforms with kubernetes
Scaling enterprise digital platforms with kubernetesScaling enterprise digital platforms with kubernetes
Scaling enterprise digital platforms with kubernetes
 
FreedomBox & Community Wi-Fi networks
FreedomBox & Community Wi-Fi networksFreedomBox & Community Wi-Fi networks
FreedomBox & Community Wi-Fi networks
 
Rendezvous with aucovei (autonomous connected car)
Rendezvous with aucovei (autonomous connected car)Rendezvous with aucovei (autonomous connected car)
Rendezvous with aucovei (autonomous connected car)
 
Role of AI & ML in beauty care industry
Role of AI & ML in beauty care industryRole of AI & ML in beauty care industry
Role of AI & ML in beauty care industry
 
Breaking down a monolith
Breaking down a monolithBreaking down a monolith
Breaking down a monolith
 
Design lean agile_thinking presentation
Design lean agile_thinking presentationDesign lean agile_thinking presentation
Design lean agile_thinking presentation
 
Scaling pipelines
Scaling pipelinesScaling pipelines
Scaling pipelines
 
Blockchain beyond bitcoin
Blockchain beyond bitcoinBlockchain beyond bitcoin
Blockchain beyond bitcoin
 
Http/2
Http/2Http/2
Http/2
 
Hardware hacking and internet of things
Hardware hacking and internet of thingsHardware hacking and internet of things
Hardware hacking and internet of things
 
Spring to Cloud - REST To Microservices
Spring to Cloud - REST To MicroservicesSpring to Cloud - REST To Microservices
Spring to Cloud - REST To Microservices
 
Serverless
ServerlessServerless
Serverless
 
Building Cloud Native Applications Using Spring Boot and Spring Cloud
Building Cloud Native Applications Using Spring Boot and Spring CloudBuilding Cloud Native Applications Using Spring Boot and Spring Cloud
Building Cloud Native Applications Using Spring Boot and Spring Cloud
 
Progressive Web Applications - The Next Gen Web Technologies
Progressive Web Applications - The Next Gen Web TechnologiesProgressive Web Applications - The Next Gen Web Technologies
Progressive Web Applications - The Next Gen Web Technologies
 
Scaling a Game Server: From 500 to 100,000 Users
Scaling a Game Server: From 500 to 100,000 UsersScaling a Game Server: From 500 to 100,000 Users
Scaling a Game Server: From 500 to 100,000 Users
 
Big Data - Need of Converged Data Platform
Big Data - Need of Converged Data PlatformBig Data - Need of Converged Data Platform
Big Data - Need of Converged Data Platform
 
Building a Data Lake - An App Dev's Perspective
Building a Data Lake - An App Dev's PerspectiveBuilding a Data Lake - An App Dev's Perspective
Building a Data Lake - An App Dev's Perspective
 
Understanding the Intelligent Cloud
Understanding the Intelligent CloudUnderstanding the Intelligent Cloud
Understanding the Intelligent Cloud
 
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
 

Recently uploaded

Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...lizamodels9
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxMurugaveni B
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxmalonesandreagweneth
 
‏‏VIRUS - 123455555555555555555555555555555555555555
‏‏VIRUS -  123455555555555555555555555555555555555555‏‏VIRUS -  123455555555555555555555555555555555555555
‏‏VIRUS - 123455555555555555555555555555555555555555kikilily0909
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)riyaescorts54
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |aasikanpl
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trssuser06f238
 
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfBUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfWildaNurAmalia2
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxpriyankatabhane
 
Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantadityabhardwaj282
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PPRINCE C P
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
Harmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms PresentationHarmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms Presentationtahreemzahra82
 

Recently uploaded (20)

Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptxSTOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
STOPPED FLOW METHOD & APPLICATION MURUGAVENI B.pptx
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
 
‏‏VIRUS - 123455555555555555555555555555555555555555
‏‏VIRUS -  123455555555555555555555555555555555555555‏‏VIRUS -  123455555555555555555555555555555555555555
‏‏VIRUS - 123455555555555555555555555555555555555555
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 tr
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfBUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptx
 
Forest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are importantForest laws, Indian forest laws, why they are important
Forest laws, Indian forest laws, why they are important
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C P
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 
Harmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms PresentationHarmful and Useful Microorganisms Presentation
Harmful and Useful Microorganisms Presentation
 

Metaprogramming Ruby - Changing program constructs at runtime

  • 2. – Suresh Pai “Do you know that Ruby has class instance variables?”
  • 4. • Inspired by Lisp, Smalltalk and Perl • Interpreted (REPL) • Object oriented (almost everything is an object) • Dynamically and strongly typed • Duck typing • Optimized for programmer happiness
  • 5. Code examples • Interactive Ruby • Logical operators and duck typing • Methods • Arrays & Hashes • Code blocks and yield • Classes, Objects • Modules and Mixins Code Samples - 001 to 004
  • 6. What is metaprogramming? • Manipulating language constructs at runtime • Define classes on the fly • Add methods to objects • Wrap methods with custom before/after behavior • Create domain specific languages
  • 8. The Ruby object model • Every value in Ruby is an object • Ruby object is a structure that contains • Some flags (frozen, tainted etc) • Array of instance variables • Reference to the class • What is missing? Code Samples - 005
  • 9. Where are the methods? • Methods exist only in classes, not objects • The methods of an object are the instance methods of its class • Ruby has methods for discovering methods including Object#methods, Module#instance_methods • Methods can be turned into objects using Object#method Code Samples - 006
  • 10. Blocks, Procs, Lambdas • Blocks are just chunks of code between do … end or { .. } • Methods can take a single block as an implicit parameter, and yield control to the block • Blocks can be turned into objects using • Proc.new • lambda or -> • The & operator • Blocks are closures, they capture the surrounding scope • Lambdas are closer to methods than Procs Code Samples - 007
  • 11. Classes • Every object is an instance of some class • Classes are objects too. A class is an instance of Class. • The name of the class (i.e, String) is a constant that refers to the Class object. • The class keyword is a scope operator where • Inside you can write code that is executable • self refers to the Class object • Classes can be created dynamically with Class.new Code Samples - 008
  • 12. Inheritance • All classes (except one) have exactly one superclass • If not otherwise specified, the superclass is Object • Object in turn inherits from BasicObject, which is the object Ruby class that doesn’t have a superclass. • A class’s superclass can be obtained with the superclass method. • The entire chain of superclasses can be obtained with the ancestors method. Code Samples - 009
  • 14. Modules • Modules are like classes, but different in a few ways • Provide a scope for defining methods • Modules are objects of class Module • Cannot create new objects from modules • Modules do not participate in the inheritance hierarchy directly, but can be included in the ancestors chain in interesting ways.
  • 15. include and prepend • Both include and prepend insert the module into the ancestors chain of the calling class (or module) • include inserts directly above the caller • prepend inserts directly below the caller • This affects what super means when used in the methods Code Samples - 009
  • 16. Singleton Methods • Ruby allows for defining methods on individual objects • They are defined only on the object, not available for others objects of the same class • Class methods are a special case of the singleton methods. They are actually singleton methods where the object happens to be a class. Code Samples - 010
  • 18. Singleton Classes • Recall that methods live only in classes, not objects. • Singleton methods cannot live in the object’s class, since that is shared by all the other objects. • Ruby creates a special singleton class for each object. Also known as meta class, virtual class or eigen class. • You can access it with singleton_class method or this syntax class << object ; end Code Samples - 011
  • 19. Object#extend • Including a module get the module’s instance methods, not the singleton methods (class methods) • So include the module in the singleton class • Or equivalently; use extend • extend module - make module’s instance methods also be singleton methods
  • 22. Open Classes • You can reopen any class and add methods to it • You can reopen any module and add methods to it • You can reopen any object and add methods to it • A.K.A monkey patching • Can use refinements to control the scope of changes Code Samples - 012
  • 23. method_missing • If Ruby cannot find a method in the ancestors chain, it invokes method_missing • Classes can redefine method_missing to respond to messages (“Ghost Methods”) • Some downsides • respond_to? Lies unless you also redefine respond_to_missing? • Ghost methods cannot be discovered with reflection • However, can be very useful sometimes: https://github.com/ jimweirich/builder
  • 24. define_method • define_method is a singleton method defined in the Module class • Takes a string/symbol, and a block to create a named instance method on the calling class • Useful for defining families of related methods Code Samples - 014
  • 25. Scope Gates • There are exactly three places where a program leaves the previous scope behind and open a new one • Class definitions • Module definitions • Methods • Overcoming scope gates • Flattening the scope • Shared scope Code Samples - 015
  • 26. Writing a DSL Code Samples - 016, 017 RedFlag is a monitor utility for the people in the sales department. It should send the sales folks a message when an order is late, when total sales are too low...basically, whenever one of many different things happens. Sales wants to monitor dozens of different events, and the list is bound to change every week or so.
  • 27. The eval family of methods Code Samples - 016, 017 • Kernel#eval can be used to evaluate any strings of code • Module#class_eval - evaluates a block in the context of an existing class • BasicObject#instance_eval - evaluates a block in the context of a specific object. Redefines self to be the receiver • class_exec and instance_exec can pass arguments to the block
  • 28. Hook methods Code Samples - 018 • Object model is an eventful place and lots of things happen there as your code runs like • Classes are inherited • Modules are mixed into classes (include, append) • Methods are defined, undefined and removed
  • 29. Code that writes code Code Samples - 019 • Your boss wants a class macro attr_checked • It should take the name of the attribute, as well as a block • The block is used for validation • If you assign a value to an attribute and the block doesn’t turn true for that value, then you get an exception • A class should gain access to attr_checked only when it includes a CheckedAttributes module
  • 30. Cons of Metaprogramming • Learning curve for new developers • Not easy to find symbols using grep • Not easy to comprehend • Needs more unit tests • Need to be more careful when extending
  • 31. – Zen Master Programmer “There is no such thing as Metaprogramming. It’s just programming all the way down.”