SlideShare una empresa de Scribd logo
1 de 64
Metaprogramming with Ruby Julie Yaunches Farooq Ali
What is Metaprogramming? ,[object Object],[object Object],[object Object],[object Object]
Metaprogramming == Programming ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exploring the plain define_method alias_method foo.send :bar instance_variable_get class_eval instance_eval module_eval instance_variable_set eval block.call Class.new method_missing class << self block.binding Foo.instance_methods method_added method_removed
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Ruby Object Model I ,[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Object Model I ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Object Model I ,[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Object Introspection ,[object Object],[object Object],[object Object]
Object Introspection: Instance Variables > @event = 'Away Day' >  instance_variable_get  '@event' => &quot;Away Day&quot; >  instance_variable_set  '@region', 'UK' > @region => &quot;UK&quot; >  instance_variables => [&quot;@event&quot;, &quot;@region&quot;]
Object Introspection: Methods > 'Away Day’. methods => [&quot;capitalize&quot;, &quot;split&quot;, &quot;strip&quot;, …] > 5. public_methods => [&quot;+&quot;, &quot;/&quot;, &quot;integer?&quot;, …]
Object Introspection: Methods > 'abc'.method(:capitalize) =>  #<Method: String#capitalize> class method strip capitalize String gsub split class method unbind arity Method to_proc call
 
Introspection in Action class Person def initialize(name, age, sex) @name = name @age = age @sex = sex end end Person.new('Farooq', 23, :male) Did we just think in a for-loop?!
Introspection in Action class Person def initialize(attributes) attributes.each do |attr, val| instance_variable_set(&quot;@#{attr}&quot;, val) end end end Person.new :name => 'Farooq',  :age => '23', :sex => :male
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
[object Object],[object Object],[object Object],[object Object],Blocks
Blocks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
[object Object],[object Object],[object Object],[object Object],Dynamic Methods
Calling methods dynamically ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
Calling methods dynamically: Why should I care? ,[object Object],[object Object],[object Object],[object Object],[object Object]
Parameterized method names ,[object Object],[object Object],[object Object],[object Object],def text_field(obj, method) iv = instance_variable_get &quot;@#{obj}&quot; val = iv.send(method) &quot;<input type='text' value='#{val}'>&quot; end
Callbacks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Callbacks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Convention-Oriented Coding ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Convention-Oriented Coding ,[object Object],[object Object],[object Object],[object Object],[object Object]
Convention-Oriented Coding ,[object Object],[object Object],[object Object]
Convention-Oriented Coding ,[object Object],[object Object],[object Object],[object Object],[object Object]
You can  define  methods on the fly too! define_method :say_hello do puts &quot;Hello World!&quot; end
define_method ,[object Object],[object Object],[object Object]
 
Dynamic Method Definition in Action class Person attr_reader :name, sex end class Person  { string name, sex; public string Name  { get {return name;} } public string Sex  { get {return sex;} } }
Dynamic Method Definition in Action class Object def Object.attr_reader(*attrs) attrs.each do |attr| define_method(attr) do instance_variable_get(&quot;@#{attr}&quot;) end end end end
Dynamic Method Definition in Action class Object def Object.attr_reader(*attrs) attrs.each do |attr| define_method(attr) do instance_variable_get(&quot;@#{attr}&quot;) end end end end
Another example: Lazy Loading class Person List<Person> friends; public List<Person> Friends { get { friends = friends ?? LoadFriends(); return friends; } }
Lazy Loading class Person lazy_loaded_attr :friends end
Lazy Loading class Object def self.lazy_loaded_attr(*attrs) attrs.each do |attr| define_method(attr) do eval &quot;@#{attr} ||= load_#{attr}&quot; end end end end
Lazy Loading class Person lazy_loaded_attr :friends, :children, :parents end class Person List<Person> friends, children, parents; public List<Person> Friends { get { friends = friends ?? LoadFriends(); return friends; } } public List<Person> Children { get { children = children ?? LoadChildren(); return children; } } public List<Person> Parents { get { parents = parents ?? LoadParents(); return parents; } } }
Declarative code class Album < ActiveRecord::Base has_many :tracks belongs_to :artist acts_as_taggable has_many :lyrics, :through => :tracks end
Declarative code with define_method class Album < ActiveRecord::Base has_many :tracks end class Album < ActiveRecord::Base def tracks Track.find :all,  :conditions => &quot;album_id=#{id}&quot; end end define_method :tracks …
Declarative code with define_method class ActiveRecord::Base def self.has_many(records) define_method(records) do foreign_key = &quot;#{self.name.underscore}_id&quot; klass = records.to_s.classify.constantize  klass.find :all, :conditions => &quot;#{foreign_key}=#{id}&quot; end end end
Person Person walk() define_method :walk define_method :everyone ? Person everyone() Define instance method: Define class method:
Person Person walk() define_method :walk define_method :everyone Person' Person' everyone() Define instance method: Define class method:
Person Person walk() define_method :walk define_method :everyone Person' Person' everyone() Define instance method: Define class method: Person everyone()
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Ruby Object Model II ,[object Object],[object Object],[object Object]
Ruby Object Model II ,[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Method Aliasing ,[object Object],[object Object],[object Object],[object Object],[object Object],class LoginService alias_method :original_login, :login end
Decorator Pattern with Aliasing class LoginService alias_method :original_login, :login def login(user,pass) log_event &quot;#{user} logging in&quot;  original_login(user,pass) end end
Decorator Pattern with Aliasing class LoginService alias_method_chain :login, :logging def login_with_logging(user,pass) log_event &quot;#{user} logging in&quot;  login_without_logging(user,pass) end end
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Evaluation Techniques ,[object Object],[object Object],[object Object],[object Object]
eval ,[object Object],> eval &quot;foo = 5&quot; > foo => 5 ,[object Object],def get_binding(str) return binding end str = &quot;hello&quot; eval &quot;str + ' Fred'&quot; ! &quot;hello Fred&quot; eval &quot;str + ' Fred'&quot;, get_binding(&quot;bye&quot;) ! &quot;bye Fred&quot;
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Outline
Hooks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hooks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hooks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hooks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Metaprogramming with Ruby ,[object Object],[object Object],[object Object],[object Object],[object Object]
Questions?

Más contenido relacionado

La actualidad más candente

Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Igalia
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework XtextSebastian Zarnekow
 
Domain-Specific Languages
Domain-Specific LanguagesDomain-Specific Languages
Domain-Specific LanguagesJavier Canovas
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 
Dive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDamith Warnakulasuriya
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNIKirill Kounik
 
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKPankaj Prateek
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Fwdays
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en inglesMarisa Torrecillas
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeDave Fancher
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

La actualidad más candente (20)

Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Domain-Specific Languages
Domain-Specific LanguagesDomain-Specific Languages
Domain-Specific Languages
 
P1
P1P1
P1
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Dive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through java
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 
Cleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional CodeCleaner Code: How Clean Code is Functional Code
Cleaner Code: How Clean Code is Functional Code
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

Destacado

デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)和明 斎藤
 
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性tomo_masakura
 
The way to the timeless way of programming
The way to the timeless way of programmingThe way to the timeless way of programming
The way to the timeless way of programmingShintaro Kakutani
 
エクストリームエンジニア1
エクストリームエンジニア1エクストリームエンジニア1
エクストリームエンジニア1T-arts
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Rubyyelogic
 

Destacado (9)

Functional Ruby
Functional RubyFunctional Ruby
Functional Ruby
 
Basic Rails Training
Basic Rails TrainingBasic Rails Training
Basic Rails Training
 
デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)
 
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
 
Design Patterns in Ruby
Design Patterns in RubyDesign Patterns in Ruby
Design Patterns in Ruby
 
Firefox-Addons
Firefox-AddonsFirefox-Addons
Firefox-Addons
 
The way to the timeless way of programming
The way to the timeless way of programmingThe way to the timeless way of programming
The way to the timeless way of programming
 
エクストリームエンジニア1
エクストリームエンジニア1エクストリームエンジニア1
エクストリームエンジニア1
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
 

Similar a Metaprogramming With Ruby

Advanced Ruby
Advanced RubyAdvanced Ruby
Advanced Rubyalkeshv
 
Meta programming
Meta programmingMeta programming
Meta programmingantho1404
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Java Programming For Android
Java Programming For AndroidJava Programming For Android
Java Programming For AndroidTechiNerd
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVMAlan Parkinson
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLê Thưởng
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Baruch Sadogursky
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013yohanbeschi
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming RailsJustus Eapen
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 

Similar a Metaprogramming With Ruby (20)

Advanced Ruby
Advanced RubyAdvanced Ruby
Advanced Ruby
 
Meta programming
Meta programmingMeta programming
Meta programming
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Java Programming For Android
Java Programming For AndroidJava Programming For Android
Java Programming For Android
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVM
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 

Último

8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environmentelijahj01012
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menzaictsugar
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMintel Group
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationAnamaria Contreras
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Anamaria Contreras
 

Último (20)

8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
Cyber Security Training in Office Environment
Cyber Security Training in Office EnvironmentCyber Security Training in Office Environment
Cyber Security Training in Office Environment
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
Call Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North GoaCall Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North Goa
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 Edition
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement Presentation
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.
 

Metaprogramming With Ruby

  • 1. Metaprogramming with Ruby Julie Yaunches Farooq Ali
  • 2.
  • 3.
  • 4. Exploring the plain define_method alias_method foo.send :bar instance_variable_get class_eval instance_eval module_eval instance_variable_set eval block.call Class.new method_missing class << self block.binding Foo.instance_methods method_added method_removed
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11. Object Introspection: Instance Variables > @event = 'Away Day' > instance_variable_get '@event' => &quot;Away Day&quot; > instance_variable_set '@region', 'UK' > @region => &quot;UK&quot; > instance_variables => [&quot;@event&quot;, &quot;@region&quot;]
  • 12. Object Introspection: Methods > 'Away Day’. methods => [&quot;capitalize&quot;, &quot;split&quot;, &quot;strip&quot;, …] > 5. public_methods => [&quot;+&quot;, &quot;/&quot;, &quot;integer?&quot;, …]
  • 13. Object Introspection: Methods > 'abc'.method(:capitalize) => #<Method: String#capitalize> class method strip capitalize String gsub split class method unbind arity Method to_proc call
  • 14.  
  • 15. Introspection in Action class Person def initialize(name, age, sex) @name = name @age = age @sex = sex end end Person.new('Farooq', 23, :male) Did we just think in a for-loop?!
  • 16. Introspection in Action class Person def initialize(attributes) attributes.each do |attr, val| instance_variable_set(&quot;@#{attr}&quot;, val) end end end Person.new :name => 'Farooq', :age => '23', :sex => :male
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.  
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32. You can define methods on the fly too! define_method :say_hello do puts &quot;Hello World!&quot; end
  • 33.
  • 34.  
  • 35. Dynamic Method Definition in Action class Person attr_reader :name, sex end class Person { string name, sex; public string Name { get {return name;} } public string Sex { get {return sex;} } }
  • 36. Dynamic Method Definition in Action class Object def Object.attr_reader(*attrs) attrs.each do |attr| define_method(attr) do instance_variable_get(&quot;@#{attr}&quot;) end end end end
  • 37. Dynamic Method Definition in Action class Object def Object.attr_reader(*attrs) attrs.each do |attr| define_method(attr) do instance_variable_get(&quot;@#{attr}&quot;) end end end end
  • 38. Another example: Lazy Loading class Person List<Person> friends; public List<Person> Friends { get { friends = friends ?? LoadFriends(); return friends; } }
  • 39. Lazy Loading class Person lazy_loaded_attr :friends end
  • 40. Lazy Loading class Object def self.lazy_loaded_attr(*attrs) attrs.each do |attr| define_method(attr) do eval &quot;@#{attr} ||= load_#{attr}&quot; end end end end
  • 41. Lazy Loading class Person lazy_loaded_attr :friends, :children, :parents end class Person List<Person> friends, children, parents; public List<Person> Friends { get { friends = friends ?? LoadFriends(); return friends; } } public List<Person> Children { get { children = children ?? LoadChildren(); return children; } } public List<Person> Parents { get { parents = parents ?? LoadParents(); return parents; } } }
  • 42. Declarative code class Album < ActiveRecord::Base has_many :tracks belongs_to :artist acts_as_taggable has_many :lyrics, :through => :tracks end
  • 43. Declarative code with define_method class Album < ActiveRecord::Base has_many :tracks end class Album < ActiveRecord::Base def tracks Track.find :all, :conditions => &quot;album_id=#{id}&quot; end end define_method :tracks …
  • 44. Declarative code with define_method class ActiveRecord::Base def self.has_many(records) define_method(records) do foreign_key = &quot;#{self.name.underscore}_id&quot; klass = records.to_s.classify.constantize klass.find :all, :conditions => &quot;#{foreign_key}=#{id}&quot; end end end
  • 45. Person Person walk() define_method :walk define_method :everyone ? Person everyone() Define instance method: Define class method:
  • 46. Person Person walk() define_method :walk define_method :everyone Person' Person' everyone() Define instance method: Define class method:
  • 47. Person Person walk() define_method :walk define_method :everyone Person' Person' everyone() Define instance method: Define class method: Person everyone()
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53. Decorator Pattern with Aliasing class LoginService alias_method :original_login, :login def login(user,pass) log_event &quot;#{user} logging in&quot; original_login(user,pass) end end
  • 54. Decorator Pattern with Aliasing class LoginService alias_method_chain :login, :logging def login_with_logging(user,pass) log_event &quot;#{user} logging in&quot; login_without_logging(user,pass) end end
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.