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

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)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Basics of Metaprogramming in Ruby