SlideShare une entreprise Scribd logo
1  sur  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?

Contenu connexe

Tendances

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
Pankaj Prateek
 

Tendances (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
 

En vedette

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
Shintaro Kakutani
 
エクストリームエンジニア1
エクストリームエンジニア1エクストリームエンジニア1
エクストリームエンジニア1
T-arts
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
yelogic
 

En vedette (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
 

Similaire à Metaprogramming With Ruby

Meta programming
Meta programmingMeta programming
Meta programming
antho1404
 
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
 
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
yohanbeschi
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
sagaroceanic11
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 

Similaire à 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
 

Dernier

Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
allensay1
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
daisycvs
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
Nauman Safdar
 

Dernier (20)

Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
 
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NSCROSS CULTURAL NEGOTIATION BY PANMISEM NS
CROSS CULTURAL NEGOTIATION BY PANMISEM NS
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTSDurg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
 
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTSJAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
 
PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptxQSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
QSM Chap 10 Service Culture in Tourism and Hospitality Industry.pptx
 
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 

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.