SlideShare a Scribd company logo
1 of 98
Download to read offline
Metaprograming
in Ruby
Brian Sam-Bodden
What’s this all about?
‣ We’ll learn...
‣ mainly about Ruby’s Meta-programming power
‣ about a language doesn’t treat you like a moron
‣ what happens when dynamic meets object-oriented
‣ why Ruby is superb for building frameworks
‣ what happens when meta-programming
‣ ...meets someone with too much free-time
Ruby
Ruby Ideals:
Programming should be fun!
“I believe people want to express themselves when they
program.They don’t want to fight with the language.
Programming languages must feel natural to
programmers.”
Matz
The language should treat you like a responsible adult!
Ruby
Ruby
is...
Ruby
is...
✓Object-Oriented
Ruby
is...
✓Object-Oriented
✓General Purpose
Ruby
is...
✓Object-Oriented
✓ Interpreted
✓General Purpose
Ruby
is...
✓Object-Oriented
✓Dynamic
✓ Interpreted
✓General Purpose
Ruby
is...
✓Object-Oriented
✓Dynamic
✓ Interpreted
✓General Purpose
✓ Garbage-collected
Ruby
is...
✓Object-Oriented
✓Reflective ✓Dynamic
✓ Interpreted
✓General Purpose
✓ Garbage-collected
Ruby
is...
✓Object-Oriented
✓Reflective ✓Dynamic
✓ Interpreted
✓General Purpose
✓ Multi-paradigm
✓ Garbage-collected
Ruby
is...
✓Object-Oriented
✓Reflective ✓Dynamic
✓ Interpreted
✓General Purpose
✓ Multi-paradigm
✓ Garbage-collected
✓Elegant
Without Ruby there would be
no Rails
Ruby’s meta-programing is the key
feature that makes Rails magical
Open
Classes
Say we have an Array like:
Say we have an Array like:
[1,2,3,4,5]
Say we have an Array like:
[1,2,3,4,5]
and we want to sum of
all of its elements
Let’s try something like:
Let’s try something like:
[1,2,3,4,5].sum
Let’s try something like:
[1,2,3,4,5].sum
Let’s try something like:
[1,2,3,4,5].sum
Rats! Doesn’t work in Ruby
Let’s try something like:
[1,2,3,4,5].sum
Rats! Doesn’t work in Ruby
… yet!
Ruby classes are
Ruby classes are
Ruby classes are
We can teach the Array class a new behavior
Ruby classes are
We can teach the Array class a new behavior
Let’s try again!
Let’s try again!
Let’s try again!
All you need to do is load the file
containing the enhancements
Code as
Data
Bend at will your code should
When code can be manipulated as data
a whole world of possibilities opens
In Ruby you can evaluate the
contents of a string
Code that invokes code,
that invokes code
Code that invokes code,
that invokes code
Code that invokes code,
that invokes code
There you go, there you go
Ruby provides the eval family of
methods for runtime execution of
code stored in strings
Ruby provides the eval family of
methods for runtime execution of
code stored in strings
Ruby provides the eval family of
methods for runtime execution of
code stored in strings
eval will evaluate any string
instance_eval can evaluate a
string or a code block
instance_eval can evaluate a
string or a code block
instance_eval can evaluate a
string or a code block
in the context of the receiver
class_eval can evaluate a string or a code block
in the context of the class or module it is called on
class_eval can evaluate a string or a code block
in the context of the class or module it is called on
In Ruby we try to think about sending a message to
an object rather than calling a method on an object
In Ruby we try to think about sending a message to
an object rather than calling a method on an object
In simple cases (above) syntactic sugar hides it,
but we can use it in interesting ways...
Meta-
programming
...is about programs that
write programs
Meta-programming
...it’s a superb tool for building
frameworks
...it’s the key ingredient for building
domain-specific languages
Ruby’s is a great vehicle for
meta-programming because it is:
dynamic and reflexive
open and malleable
clean syntax
code is data, data is code
programming event model
...uses meta-programming to bring
the language closer to the problem
...is a collection of domain-specific
languages (DSL) for building web
applications
Ruby on Rails
Singleton
Class
In Ruby you can enhance a
particular instance of a class
Ruby uses a proxy class known as
the singleton class
Meta-class:The singleton for
Class objects
class_eval indirectly uses the meta-class
adding a singleton method to the class
Rails relies heavily on Ruby’s ability
to dynamically enhance a class
Rails relies heavily on Ruby’s ability
to dynamically enhance a class
Shortcuts such as define_method
exist to make life easier
Accessing the singleton meta-class
explicitly
Child classes get enhanced with
class methods
Inheritance
the Ruby Way
Many Ruby DSLs create class
methods on subclasses using the
meta-class (singleton class)
Rails uses this technique in ActiveRecord
A module with a “Base” class
Methods get added to our classes with
simple declarations
Getting closer to a DSL!
Now our class has a new set of class
methods
Now our class has a new set of class
methods
AOP
the Ruby
Way
With alias_method you can wrap
an existing method...
...effectively intercepting any calls
and injecting any desired behavior
...effectively intercepting any calls
and injecting any desired behavior
Meta-Programming
Events
Ruby has a rich event model
associated with static and dynamic
changes of the code
Included Hook
Method Missing
Ruby provides several hook
methods that can be used to created
custom behaviors
method_missing
method_added
method_removed
Ruby’s Markup Builder is an
example of what can be achieved
with method missing
Let’s implement the greeter example
using method_missing
greeter using method_missing
greeter using method_missing
Trellis...or what happens when you have too much time
in between consulting gigs
and your friends no longer call you
I was bored...
In the Ruby world I’ve worked with Rails and Merb
...thinking of web apps in terms of request & response
meanwhile... in the Java world I was working with
Tapestry and Wicket
...thinking about Pages, Components and Events
Started to hack to see what it would be to build
something like Tapestry/Wicket in Ruby
...actually it all started as an learning exercise
...but then I kept going
...somehow I ended building component-oriented
web framework in Ruby
...part of a conversation among friends about the need
for IoC and AOP frameworks for dynamic languages
You might be
asking yourself,
but why?
Why not?
My goals:
✓Magic like Rails; less code more action
✓ Small like Camping... a micro-framework
✓Components like Tapestry/Wicket
✓Clean HTML templates...
✓...but also programatic HTML generation
✓Non-managed components, no pooling
The big picture:
Trellis Application
Pages Components
has
has
{declares pages used
declares a home page
dispatches request to pages
} {
defines a template
provides event handlers
passes events to the
components
provides reusable logic
responds to events
can be stateless (tags)
or stateful
The simplest Trellis App, one Application and one Page
The Code
The Template
What did I use to put this thing together...
➡A boat load of meta-programming
➡Rack ...HTTP the Ruby way
➡Radius ...XML tags for the templates
➡Builder ...for building HTML/XML
➡Hpricot, REXML ...parsing searching HTML/XML
➡Paginator ...for duh, pagination
➡Parts of Rails ...so far ActiveSupport (Inflectors)
Let’s do some code spelunking on the Trellis codebase...
yes, there are some things that I’m not proud of but...
...this is pre-alpha, unreleased v0.000001;-)
Some of the example applications that I’ve put
together in order of complexity
➡hilo
➡guest_book
➡hangman
➡yui
➡stateful_counters
➡flickr
➡simple_blog
➡crud_components
What have
we learned?
There is more to Ruby than Rails!
Building a Framework?
Give Ruby a try!
Build the language up towards
the problem
Rack: http://rack.rubyforge.org
Radius: http://radius.rubyforge.org
Hpricot: http://code.whytheluckystiff.net/hpricot
REXML: http://www.germane-software.com/software/rexml
Builder: http://builder.rubyforge.org
Paginator: http://paginator.rubyforge.org
YUI (Yahoo! UI Library): http://open.yahoo.com/yui
Trellis (Not ReleasedYet)
Trellis @ RubyForge: http://rubyforge.org/projects/trellis
Trellis Website: http://www.trellisframework.org
Resources
www.integrallis.com

More Related Content

What's hot

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - Basic
Eddie Kao
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
Ashiq Uz Zoha
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
Kumar
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
rahulsahay19
 
Paca oops slid
Paca oops slidPaca oops slid
Paca oops slid
pacatarpit
 
OOP programming
OOP programmingOOP programming
OOP programming
anhdbh
 

What's hot (20)

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - Basic
 
Beginning OOP in PHP
Beginning OOP in PHPBeginning OOP in PHP
Beginning OOP in PHP
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
Intro Ruby Classes Part I
Intro Ruby Classes Part IIntro Ruby Classes Part I
Intro Ruby Classes Part I
 
Constructors, Intro to Ruby Classes Part II
Constructors, Intro to Ruby Classes Part IIConstructors, Intro to Ruby Classes Part II
Constructors, Intro to Ruby Classes Part II
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
 
Ruby On Rails Overview
Ruby On Rails OverviewRuby On Rails Overview
Ruby On Rails Overview
 
Backend roadmap
Backend roadmapBackend roadmap
Backend roadmap
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Ruby an overall approach
Ruby an overall approachRuby an overall approach
Ruby an overall approach
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascript
 
Java script
Java scriptJava script
Java script
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Core java programming tutorial - Brainsmartlabs
Core java programming tutorial - BrainsmartlabsCore java programming tutorial - Brainsmartlabs
Core java programming tutorial - Brainsmartlabs
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
 
Paca oops slid
Paca oops slidPaca oops slid
Paca oops slid
 
OOP programming
OOP programmingOOP programming
OOP programming
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 

Viewers also liked

Viewers also liked (6)

RailsConf 2013: RubyMotion
RailsConf 2013: RubyMotionRailsConf 2013: RubyMotion
RailsConf 2013: RubyMotion
 
Integrallis groovy-cloud
Integrallis groovy-cloudIntegrallis groovy-cloud
Integrallis groovy-cloud
 
Trellis Framework At RubyWebConf
Trellis Framework At RubyWebConfTrellis Framework At RubyWebConf
Trellis Framework At RubyWebConf
 
Road to mobile w/ Sinatra, jQuery Mobile, Spine.js and Mustache
Road to mobile w/ Sinatra, jQuery Mobile, Spine.js and MustacheRoad to mobile w/ Sinatra, jQuery Mobile, Spine.js and Mustache
Road to mobile w/ Sinatra, jQuery Mobile, Spine.js and Mustache
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
 

Similar to Ruby Metaprogramming - OSCON 2008

Ruby tutorial
Ruby tutorialRuby tutorial
Ruby tutorial
knoppix
 
Ruby and Rails short motivation
Ruby and Rails short motivationRuby and Rails short motivation
Ruby and Rails short motivation
jistr
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
tutorialsruby
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
tutorialsruby
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
sunniboy
 

Similar to Ruby Metaprogramming - OSCON 2008 (20)

Ruby Metaprogramming 08
Ruby Metaprogramming 08Ruby Metaprogramming 08
Ruby Metaprogramming 08
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby tutorial
Ruby tutorialRuby tutorial
Ruby tutorial
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Ruby and Rails short motivation
Ruby and Rails short motivationRuby and Rails short motivation
Ruby and Rails short motivation
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Rails Vs CakePHP
Rails Vs CakePHPRails Vs CakePHP
Rails Vs CakePHP
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
 
Devoxx%202008%20Tutorial
Devoxx%202008%20TutorialDevoxx%202008%20Tutorial
Devoxx%202008%20Tutorial
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
Exploring Ruby on Rails and PostgreSQL
Exploring Ruby on Rails and PostgreSQLExploring Ruby on Rails and PostgreSQL
Exploring Ruby on Rails and PostgreSQL
 
Introduction to Ruby & Modern Programming
Introduction to Ruby & Modern ProgrammingIntroduction to Ruby & Modern Programming
Introduction to Ruby & Modern Programming
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on Rails
Ruby on Rails Ruby on Rails
Ruby on Rails
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on Rails 3 Day BC
Ruby on Rails 3 Day BCRuby on Rails 3 Day BC
Ruby on Rails 3 Day BC
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Ruby Metaprogramming - OSCON 2008