SlideShare uma empresa Scribd logo
1 de 98
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

Destaque (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)
 

Semelhante a 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
 

Semelhante a 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
 

Último

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Ruby Metaprogramming - OSCON 2008