SlideShare uma empresa 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?

Mais conteúdo relacionado

Mais procurados

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
 

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

Destaque

デザインパターン(初歩的な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
 

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

Semelhante 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
 

Semelhante 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

Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Delhi Call girls
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Centuryrwgiffor
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMRavindra Nath Shukla
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsMichael W. Hawkins
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetCreating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetDenis Gagné
 
RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataExhibitors Data
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxWorkforce Group
 
A305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdfA305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdftbatkhuu1
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...lizamodels9
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxAndy Lambert
 

Último (20)

Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSM
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael Hawkins
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature SetCreating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
Creating Low-Code Loan Applications using the Trisotech Mortgage Feature Set
 
RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors Data
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptx
 
A305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdfA305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdf
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 

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.