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

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
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...Any kyc Account
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Roland Driesen
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
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
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageMatteo Carbone
 
Unlocking the Secrets of Affiliate Marketing.pdf
Unlocking the Secrets of Affiliate Marketing.pdfUnlocking the Secrets of Affiliate Marketing.pdf
Unlocking the Secrets of Affiliate Marketing.pdfOnline Income Engine
 
BEST ✨ Call Girls In Indirapuram Ghaziabad ✔️ 9871031762 ✔️ Escorts Service...
BEST ✨ Call Girls In  Indirapuram Ghaziabad  ✔️ 9871031762 ✔️ Escorts Service...BEST ✨ Call Girls In  Indirapuram Ghaziabad  ✔️ 9871031762 ✔️ Escorts Service...
BEST ✨ Call Girls In Indirapuram Ghaziabad ✔️ 9871031762 ✔️ Escorts Service...noida100girls
 
Event mailer assignment progress report .pdf
Event mailer assignment progress report .pdfEvent mailer assignment progress report .pdf
Event mailer assignment progress report .pdftbatkhuu1
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Roland Driesen
 
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
 
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
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
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
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 

Ú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
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
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
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Unlocking the Secrets of Affiliate Marketing.pdf
Unlocking the Secrets of Affiliate Marketing.pdfUnlocking the Secrets of Affiliate Marketing.pdf
Unlocking the Secrets of Affiliate Marketing.pdf
 
BEST ✨ Call Girls In Indirapuram Ghaziabad ✔️ 9871031762 ✔️ Escorts Service...
BEST ✨ Call Girls In  Indirapuram Ghaziabad  ✔️ 9871031762 ✔️ Escorts Service...BEST ✨ Call Girls In  Indirapuram Ghaziabad  ✔️ 9871031762 ✔️ Escorts Service...
BEST ✨ Call Girls In Indirapuram Ghaziabad ✔️ 9871031762 ✔️ Escorts Service...
 
Event mailer assignment progress report .pdf
Event mailer assignment progress report .pdfEvent mailer assignment progress report .pdf
Event mailer assignment progress report .pdf
 
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
Nepali Escort Girl Kakori \ 9548273370 Indian Call Girls Service Lucknow ₹,9517
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...
 
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
 
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
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
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
 
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...
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 

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.