SlideShare a Scribd company logo
1 of 15
Download to read offline
Basics of Metaprogramming
Tamás Tompa (Digital Natives)
tamas.tompa@digitalnatives.hu
Budapest Ruby Meetup 2013
02/10/2013
Thursday, October 3, 13
“Metaprogramming is writing code
that writes code.”
Thursday, October 3, 13
what for?
§ examples
§ writing a wrapper
§ DSL (domain specific language)
§ keep your code DRY
§ extend core ruby classes
Thursday, October 3, 13
runtime
§ static vs dynamic metaprogramming
§ everything is object (even classes)
§ code introspection
Thursday, October 3, 13
well known example
§ ActiveRecord::Base
§ reads the schema at runtime
§ discovers fields
§ conventions
Thursday, October 3, 13
monkey patching
§ monkey patch is a way to extend or
modify the run-time code of dynamic
languages without altering the original
source code
§ can be dangerous
§ always carefully check the existing
methods
Thursday, October 3, 13
basics
obj = MyClass.new
obj.class # => MyClass
"hello".class # => String
String.class # => Class
obj.instance_variables # => [:@v]
obj.methods.grep(/my/) # => [:my_method]
Class.instance_methods(false)
Thursday, October 3, 13
basics
# ignore inherited methods
Class.instance_methods(false)
String.superclass # => Object
Object.superclass # => BasicObject
BasicObject.superclass # => nil
# module and kernel
D.ancestors # => [D, C, M, Object,
Kernel, BasicObject]
Thursday, October 3, 13
“Classes themselves are nothing
but objects.”
Thursday, October 3, 13
object model
Thursday, October 3, 13
dynamic methods
class MyClass
define_method :my_method do |my_arg|
my_arg * 3
end
end
obj = MyClass.new
obj.my_method(2) # => 6
obj.send(:my_method, 2) # => 6
Thursday, October 3, 13
generating methods
class Computer
def initialize(computer_id, data_source)
end
def self.define_component(name)
define_method(name) do
info = @data_source.send "get_#{name}_info" , @id
price = @data_source.send "get_#{name}_price" , @id
end
end
define_component :mouse
define_component :cpu
end
Thursday, October 3, 13
method missing
class Lawyer
def method_missing(method, *args)
puts "You called: #{method}(#{args.join(', ')})"
puts "(You also passed it a block)" if block_given?
end
end
bob = Lawyer.new
bob.talk_simple('a' , 'b' ) do
# a block
end
You called: talk_simple(a, b)
(You also passed it a block)
Thursday, October 3, 13
http://pragprog.com/book/ppmetr/metaprogramming-ruby
Thursday, October 3, 13
We’re hiring!
http://digitalnatives.hu/jobs
Thursday, October 3, 13

More Related Content

Viewers also liked (6)

Evolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital NativesEvolution of the Software Development Process ad Digital Natives
Evolution of the Software Development Process ad Digital Natives
 
Ruby meetup 7_years_in_testing
Ruby meetup 7_years_in_testingRuby meetup 7_years_in_testing
Ruby meetup 7_years_in_testing
 
Testing in JavaScript
Testing in JavaScriptTesting in JavaScript
Testing in JavaScript
 
Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09Digital natives incubation process_2011-11-23_v09
Digital natives incubation process_2011-11-23_v09
 
JRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazsJRuby talk / 26.03.2014 / @vbalazs
JRuby talk / 26.03.2014 / @vbalazs
 
Kanban Basics for Beginners
Kanban Basics for BeginnersKanban Basics for Beginners
Kanban Basics for Beginners
 

Similar to Basics of Metaprogramming in Ruby

Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twig
markstory
 
Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02
sagaroceanic11
 

Similar to Basics of Metaprogramming in Ruby (20)

Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013   Symfony2 and MongoDB - MidwestPHP 2013
Symfony2 and MongoDB - MidwestPHP 2013
 
Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twig
 
ADAM
ADAMADAM
ADAM
 
Caching tips
Caching tipsCaching tips
Caching tips
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs Scalability
 
Using MRuby in a database
Using MRuby in a databaseUsing MRuby in a database
Using MRuby in a database
 
Ruby Programming
Ruby ProgrammingRuby Programming
Ruby Programming
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
Ruby on rails - Ruby Basics
Ruby on rails - Ruby BasicsRuby on rails - Ruby Basics
Ruby on rails - Ruby Basics
 
Ruby on Rails 3 Day BC
Ruby on Rails 3 Day BCRuby on Rails 3 Day BC
Ruby on Rails 3 Day BC
 
Ruby
RubyRuby
Ruby
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
 
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
JavaScript nicht nur für Programmierer: Einblicke in die weltweit am meisten ...
 
Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
 
Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02Rubyonrails 120409061835-phpapp02
Rubyonrails 120409061835-phpapp02
 
Groovy Metaprogramming for Dummies
Groovy Metaprogramming for DummiesGroovy Metaprogramming for Dummies
Groovy Metaprogramming for Dummies
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 

More from Digital Natives

Budapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails DeploymentBudapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails Deployment
Digital Natives
 

More from Digital Natives (11)

How to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup SafaryHow to support innovation in organisations @ Startup Safary
How to support innovation in organisations @ Startup Safary
 
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
A termékfejlesztés rögös útja (avagy barangolás a módszertanok és eszközök er...
 
Agile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup SafaryAgile és lean workshop @ Startup Safary
Agile és lean workshop @ Startup Safary
 
Introduction to GraphQL with Ruby
Introduction to GraphQL with RubyIntroduction to GraphQL with Ruby
Introduction to GraphQL with Ruby
 
A visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patternsA visual introduction to concurrency and parallellism patterns
A visual introduction to concurrency and parallellism patterns
 
How flat organisations support the innovation
How flat organisations support the innovationHow flat organisations support the innovation
How flat organisations support the innovation
 
CULTURE OF INNOVATION
CULTURE OF INNOVATIONCULTURE OF INNOVATION
CULTURE OF INNOVATION
 
Mixgar in Volt festival 2011
Mixgar in Volt festival 2011Mixgar in Volt festival 2011
Mixgar in Volt festival 2011
 
Mixgar prezi v1.2
Mixgar prezi v1.2Mixgar prezi v1.2
Mixgar prezi v1.2
 
Budapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails DeploymentBudapest.rb 2011/01 - Rails Deployment
Budapest.rb 2011/01 - Rails Deployment
 
Budapest.rb 201010
Budapest.rb 201010Budapest.rb 201010
Budapest.rb 201010
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 

Basics of Metaprogramming in Ruby