SlideShare a Scribd company logo
Metaprogramming with Ruby Julie Yaunches Farooq Ali
What is Metaprogramming? Code that writes code Know Thyself Reflection.kind_of? Metaprogramming Compile-time vs. Runtime
Metaprogramming == Programming No natural separation Ruby is interpreted, not compiled Everything’s an object. Even classes! Extensible type system "Meta, shmeta!  Learning Ruby isn’t like scaling a mountain. It’s more like exploring a plain. " - David Black
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
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Ruby Object Model I Everything is an instance of Object Every object has a number of things: klass, superclass, methods  Developer = Class.new  julie = Developer.new
Ruby Object Model I Module – a collection of methods and constants Methods can be instance methods or module methods Modules can be ‘mixedin’ to a class. module British def goes_to_pub   “ I love beer and geeky talk” end end class Developer include British end julie.goes_to_pub =>  “I love beer and geeky talk”
Ruby Object Model I When you create a module, it’s methods become available to the instances of the class via a proxy class.
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Object Introspection Instance variables Instance Methods Class scope via singleton class
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
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Most common usage… Loop extraction… means of iterating Blocks are basically nameless functions. You can pass a a block to another function, and then that function can invoke the passed-in nameless function. Callbacks and hooks (will see later) Can be passed all over the place for really any sort of need. Blocks
Blocks Blocks are basically nameless functions. You can pass a a block to another function, and then that function can invoke the passed-in nameless function. def foo yield end foo {puts “foo”} => “foo” foo {puts “bar”} => “bar” Iterating through a collection Records.each do |record| print_title end Encapsulating error prone procedures open(“some_file”) do |input| input.each_line do |line| process_input_line line end end
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Calling methods dynamically Convention-Oriented coding Defining them on the fly Writing declarative code Dynamic Methods
Calling methods dynamically > a = &quot;Hello World!&quot; => &quot;Hello World!&quot; > a.downcase => &quot;hello world!&quot; >  a.send(:downcase) => &quot;hello world!&quot;
 
Calling methods dynamically: Why should I care? Parameterized method names Callbacks and Observers Convention-oriented code Working with method collections and more…
Parameterized method names controller: @person = Person.new('Farooq') view: <%= text_field :person, :name %> 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 class VaultController < BankController before_filter :authorize  private def authorize user.can_access?(vault) end end
Callbacks class SymbolFilter < Filter def initialize(filter) @filter = filter end def call(controller, &block) controller.send(@filter, &block) end end
Convention-Oriented Coding class CreditCard def validate validate_number  validate_expiration end private def validate_number ... end def validate_expiration ... end end
Convention-Oriented Coding def validate methods.grep /^validate_/ do |m| self.send m end end
Convention-Oriented Coding class CreditCard validate :number, :expiration end
Convention-Oriented Coding def validate(*validations) validations.each do |v| self.send &quot;validate_#{v}&quot; end end
You can  define  methods on the fly too! define_method :say_hello do puts &quot;Hello World!&quot; end
define_method Defines an instance method on a class Can define class methods via singleton Great for writing declarative code
 
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()
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Ruby Object Model II You can open any object and define methods on it. Developer = Class.new Developer.instance_eval do   def pairing   “julie and farooq are pairing&quot;   end end Developer.class_eval do   def write_code   “type type type&quot;   end end Developer.write_code #=> undefined method ‘write_code’ for Foo:Class Developer.new. write_code #=> “type type type&quot; Developer.pairing #=> &quot; julie and farooq are pairing&quot; Developer.new.pairing #=> undefined method ‘baz’ for #<Foo:0x7dce8>
Ruby Object Model II We’ve now opened and defined methods on both the instance of Class Developer and all instances of Class Developer. When you define methods on an instance of an object, you are defining them on it’s ‘metaclass’ or singleton.
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing Evaluation techniques Object lifecycle hooks and method_missing Outline
Method Aliasing Clones a method Popularly used in decorators AOP &quot;around advice&quot;  LISP around method combinator Monkey patches 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
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Evaluation Techniques Evaluate code at runtime In instance and class scopes With different block bindings eval, instance_eval, class_eval, module_eval
eval Evaluates a string > eval &quot;foo = 5&quot; > foo => 5 Optional binding 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;
Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
Hooks Allow you to trap some event, such as object creation… Example – adding a timestamp to every object created. (Taken from the pickaxe) class Object   attr_accessor :timestamp end class Class   alias_method :old_new, :new   def new(*args)   result = old_new(*args)   result.timestamp = Time.now   result   end end
Hooks You can know when a Module was included in another Object definition. module A    def A.included(mod)    puts &quot;#{self} included in #{mod}“   end end  module Enumerable    include A end  This is done via a call to append_features on the module doing the including
Hooks method_missing method_added method_removed You can hook into any of these and perform some operation when something happens to object under consideration. class Foo   def method_missing(methodname, *args)   #log something   #handle in some way   end end
Hooks Can allow you to hook into how your plugins are intialized with Rails. Rails uses something called Rails::Plugin::Loader  You can hook into this Rails::Initializer.run do |config|  config.plugin_loader = PluginLoaderWithDependencies  End Similarly, hooking into other framework type stuff (like ActiveRecord or even Subversion) is possible
Metaprogramming with Ruby No longer black magic Fresh design patterns Declarative programming Higher level of abstraction Tone down the YAGNI
Questions?
Ad

More Related Content

What's hot (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)
Igalia
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
Sebastian Zarnekow
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Domain-Specific Languages
Domain-Specific LanguagesDomain-Specific Languages
Domain-Specific Languages
Javier Canovas
 
P1
P1P1
P1
Actuaria, Facultad de Ciencias, UNAM
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
Mindfire Solutions
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed 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 java
Damith Warnakulasuriya
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
Kirill Kounik
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
Dot Com Infoway - Custom Software, Mobile, Web Application Development and Digital Marketing Company
 
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
 
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 ingles
Marisa Torrecillas
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
Jussi Pohjolainen
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
Michael Girouard
 
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
Dave 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 Kute
Tushar B Kute
 
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 Programming
Sehwan Noh
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
Sebastian Zarnekow
 
Domain-Specific Languages
Domain-Specific LanguagesDomain-Specific Languages
Domain-Specific Languages
Javier Canovas
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed 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 java
Damith Warnakulasuriya
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
Kirill 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 IITK
Pankaj 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 ingles
Marisa 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 Code
Dave 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 Kute
Tushar B Kute
 

Viewers also liked (9)

Functional Ruby
Functional RubyFunctional Ruby
Functional Ruby
Amoniac OÜ
 
Basic Rails Training
Basic Rails TrainingBasic Rails Training
Basic Rails Training
Arthit Hongchintakul
 
デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)デザインパターン(初歩的な7パターン)
デザインパターン(初歩的な7パターン)
和明 斎藤
 
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
tomo_masakura
 
Design Patterns in Ruby
Design Patterns in RubyDesign Patterns in Ruby
Design Patterns in Ruby
Mindfire Solutions
 
Firefox-Addons
Firefox-AddonsFirefox-Addons
Firefox-Addons
Mindfire Solutions
 
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
 
デザインパターン(初歩的な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 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
 
Ad

Similar to Metaprogramming With Ruby (20)

Advanced Ruby
Advanced RubyAdvanced Ruby
Advanced Ruby
alkeshv
 
Meta programming
Meta programmingMeta programming
Meta programming
antho1404
 
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 Android
TechiNerd
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
Cory Foy
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVM
Alan Parkinson
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
Mike Bowler
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
HamletDRC
 
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 Everything
noelrap
 
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 2013
yohanbeschi
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
Justus Eapen
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
Michael Koby
 
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
 
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
Python Ireland
 
Advanced Ruby
Advanced RubyAdvanced Ruby
Advanced Ruby
alkeshv
 
Meta programming
Meta programmingMeta programming
Meta programming
antho1404
 
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 Android
TechiNerd
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
Cory Foy
 
Test automation with Cucumber-JVM
Test automation with Cucumber-JVMTest automation with Cucumber-JVM
Test automation with Cucumber-JVM
Alan Parkinson
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
Mike Bowler
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
HamletDRC
 
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 Everything
noelrap
 
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 2013
yohanbeschi
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
Justus Eapen
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
Michael Koby
 
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
 
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
Python Ireland
 
Ad

Recently uploaded (20)

Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdfRackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
ericnewman522
 
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdfBest Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Cashapp Profile
 
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdfVannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
ovanveen
 
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining LiquidityThe Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
xnayankumar
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWSThe Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
Continuity and Resilience
 
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Chandigarh
 
How AI Helps HR Lead Better, Not Just Work Faster
How AI Helps HR Lead Better, Not Just Work FasterHow AI Helps HR Lead Better, Not Just Work Faster
How AI Helps HR Lead Better, Not Just Work Faster
Aginto - A Digital Agency
 
Presentation - The Evolution of the Internet.pdf
Presentation - The Evolution of the Internet.pdfPresentation - The Evolution of the Internet.pdf
Presentation - The Evolution of the Internet.pdf
kasierra8090
 
Outsourcing Finance and accounting services
Outsourcing Finance and accounting servicesOutsourcing Finance and accounting services
Outsourcing Finance and accounting services
Intellgus
 
A. Stotz All Weather Strategy - Performance review April 2025
A. Stotz All Weather Strategy - Performance review April 2025A. Stotz All Weather Strategy - Performance review April 2025
A. Stotz All Weather Strategy - Performance review April 2025
FINNOMENAMarketing
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
Continuity and Resilience
 
A Brief Introduction About Quynh Keiser
A Brief Introduction  About Quynh KeiserA Brief Introduction  About Quynh Keiser
A Brief Introduction About Quynh Keiser
Quynh Keiser
 
Solving Disintermediation in Ride-Hailing
Solving Disintermediation in Ride-HailingSolving Disintermediation in Ride-Hailing
Solving Disintermediation in Ride-Hailing
xnayankumar
 
AlaskaSilver Corporate Presentation May_2025_Long.pdf
AlaskaSilver Corporate Presentation May_2025_Long.pdfAlaskaSilver Corporate Presentation May_2025_Long.pdf
AlaskaSilver Corporate Presentation May_2025_Long.pdf
vanessa47939
 
Eric Hannelius - A Serial Entrepreneur
Eric  Hannelius  -  A Serial EntrepreneurEric  Hannelius  -  A Serial Entrepreneur
Eric Hannelius - A Serial Entrepreneur
Eric Hannelius
 
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
mjenkins13
 
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdfCloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Brij Consulting, LLC
 
IT Support Company Profile by Slidesgo.pptx
IT Support Company Profile by Slidesgo.pptxIT Support Company Profile by Slidesgo.pptx
IT Support Company Profile by Slidesgo.pptx
ahmed gamal
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty AliThe Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
Continuity and Resilience
 
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella
 
Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdfRackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
Rackspace-White-Paper-OpenStack-PRI-TSK-11768-5.pdf
ericnewman522
 
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdfBest Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Best Places Buy Verified Cash App Accounts- Reviewed (pdf).pdf
Cashapp Profile
 
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdfVannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
Vannin Healthcare Greencube Electronic Health Record -Modules and Features.pdf
ovanveen
 
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining LiquidityThe Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
The Profitability Paradox: How Dunzo Can Scale AOV While Maintaining Liquidity
xnayankumar
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWSThe Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - AWS
Continuity and Resilience
 
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Visits PEC Chandigarh_ Bridging Academia and Infrastructure Inno...
Kunal Bansal Chandigarh
 
How AI Helps HR Lead Better, Not Just Work Faster
How AI Helps HR Lead Better, Not Just Work FasterHow AI Helps HR Lead Better, Not Just Work Faster
How AI Helps HR Lead Better, Not Just Work Faster
Aginto - A Digital Agency
 
Presentation - The Evolution of the Internet.pdf
Presentation - The Evolution of the Internet.pdfPresentation - The Evolution of the Internet.pdf
Presentation - The Evolution of the Internet.pdf
kasierra8090
 
Outsourcing Finance and accounting services
Outsourcing Finance and accounting servicesOutsourcing Finance and accounting services
Outsourcing Finance and accounting services
Intellgus
 
A. Stotz All Weather Strategy - Performance review April 2025
A. Stotz All Weather Strategy - Performance review April 2025A. Stotz All Weather Strategy - Performance review April 2025
A. Stotz All Weather Strategy - Performance review April 2025
FINNOMENAMarketing
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Murphy -Dat...
Continuity and Resilience
 
A Brief Introduction About Quynh Keiser
A Brief Introduction  About Quynh KeiserA Brief Introduction  About Quynh Keiser
A Brief Introduction About Quynh Keiser
Quynh Keiser
 
Solving Disintermediation in Ride-Hailing
Solving Disintermediation in Ride-HailingSolving Disintermediation in Ride-Hailing
Solving Disintermediation in Ride-Hailing
xnayankumar
 
AlaskaSilver Corporate Presentation May_2025_Long.pdf
AlaskaSilver Corporate Presentation May_2025_Long.pdfAlaskaSilver Corporate Presentation May_2025_Long.pdf
AlaskaSilver Corporate Presentation May_2025_Long.pdf
vanessa47939
 
Eric Hannelius - A Serial Entrepreneur
Eric  Hannelius  -  A Serial EntrepreneurEric  Hannelius  -  A Serial Entrepreneur
Eric Hannelius - A Serial Entrepreneur
Eric Hannelius
 
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
2025 May - Prospect & Qualify Leads for B2B in Hubspot - Demand Gen HUG.pptx
mjenkins13
 
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdfCloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Cloud Stream Part II Mobile Hub V2 Cloud Confluency.pdf
Brij Consulting, LLC
 
IT Support Company Profile by Slidesgo.pptx
IT Support Company Profile by Slidesgo.pptxIT Support Company Profile by Slidesgo.pptx
IT Support Company Profile by Slidesgo.pptx
ahmed gamal
 
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty AliThe Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
The Business Conference and IT Resilience Summit Abu Dhabi, UAE - Abdelmoaty Ali
Continuity and Resilience
 
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella: A Life of Accomplishment, Service, Resiliency.
Allan Kinsella
 

Metaprogramming With Ruby

  • 1. Metaprogramming with Ruby Julie Yaunches Farooq Ali
  • 2. What is Metaprogramming? Code that writes code Know Thyself Reflection.kind_of? Metaprogramming Compile-time vs. Runtime
  • 3. Metaprogramming == Programming No natural separation Ruby is interpreted, not compiled Everything’s an object. Even classes! Extensible type system &quot;Meta, shmeta! Learning Ruby isn’t like scaling a mountain. It’s more like exploring a plain. &quot; - David Black
  • 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. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 6. Ruby Object Model I Everything is an instance of Object Every object has a number of things: klass, superclass, methods Developer = Class.new julie = Developer.new
  • 7. Ruby Object Model I Module – a collection of methods and constants Methods can be instance methods or module methods Modules can be ‘mixedin’ to a class. module British def goes_to_pub “ I love beer and geeky talk” end end class Developer include British end julie.goes_to_pub => “I love beer and geeky talk”
  • 8. Ruby Object Model I When you create a module, it’s methods become available to the instances of the class via a proxy class.
  • 9. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 10. Object Introspection Instance variables Instance Methods Class scope via singleton class
  • 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. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 18. Most common usage… Loop extraction… means of iterating Blocks are basically nameless functions. You can pass a a block to another function, and then that function can invoke the passed-in nameless function. Callbacks and hooks (will see later) Can be passed all over the place for really any sort of need. Blocks
  • 19. Blocks Blocks are basically nameless functions. You can pass a a block to another function, and then that function can invoke the passed-in nameless function. def foo yield end foo {puts “foo”} => “foo” foo {puts “bar”} => “bar” Iterating through a collection Records.each do |record| print_title end Encapsulating error prone procedures open(“some_file”) do |input| input.each_line do |line| process_input_line line end end
  • 20. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 21. Calling methods dynamically Convention-Oriented coding Defining them on the fly Writing declarative code Dynamic Methods
  • 22. Calling methods dynamically > a = &quot;Hello World!&quot; => &quot;Hello World!&quot; > a.downcase => &quot;hello world!&quot; > a.send(:downcase) => &quot;hello world!&quot;
  • 23.  
  • 24. Calling methods dynamically: Why should I care? Parameterized method names Callbacks and Observers Convention-oriented code Working with method collections and more…
  • 25. Parameterized method names controller: @person = Person.new('Farooq') view: <%= text_field :person, :name %> def text_field(obj, method) iv = instance_variable_get &quot;@#{obj}&quot; val = iv.send(method) &quot;<input type='text' value='#{val}'>&quot; end
  • 26. Callbacks class VaultController < BankController before_filter :authorize private def authorize user.can_access?(vault) end end
  • 27. Callbacks class SymbolFilter < Filter def initialize(filter) @filter = filter end def call(controller, &block) controller.send(@filter, &block) end end
  • 28. Convention-Oriented Coding class CreditCard def validate validate_number validate_expiration end private def validate_number ... end def validate_expiration ... end end
  • 29. Convention-Oriented Coding def validate methods.grep /^validate_/ do |m| self.send m end end
  • 30. Convention-Oriented Coding class CreditCard validate :number, :expiration end
  • 31. Convention-Oriented Coding def validate(*validations) validations.each do |v| self.send &quot;validate_#{v}&quot; end end
  • 32. You can define methods on the fly too! define_method :say_hello do puts &quot;Hello World!&quot; end
  • 33. define_method Defines an instance method on a class Can define class methods via singleton Great for writing declarative code
  • 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. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 49. Ruby Object Model II You can open any object and define methods on it. Developer = Class.new Developer.instance_eval do def pairing “julie and farooq are pairing&quot; end end Developer.class_eval do def write_code “type type type&quot; end end Developer.write_code #=> undefined method ‘write_code’ for Foo:Class Developer.new. write_code #=> “type type type&quot; Developer.pairing #=> &quot; julie and farooq are pairing&quot; Developer.new.pairing #=> undefined method ‘baz’ for #<Foo:0x7dce8>
  • 50. Ruby Object Model II We’ve now opened and defined methods on both the instance of Class Developer and all instances of Class Developer. When you define methods on an instance of an object, you are defining them on it’s ‘metaclass’ or singleton.
  • 51. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 52. Method Aliasing Clones a method Popularly used in decorators AOP &quot;around advice&quot; LISP around method combinator Monkey patches class LoginService alias_method :original_login, :login end
  • 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. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 56. Evaluation Techniques Evaluate code at runtime In instance and class scopes With different block bindings eval, instance_eval, class_eval, module_eval
  • 57. eval Evaluates a string > eval &quot;foo = 5&quot; > foo => 5 Optional binding 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;
  • 58. Ruby object model I: classes, objects, modules and blocks Object introspection Blocks and the strategy pattern Dynamic methods Ruby object model II: singletons and open classes Method aliasing and the decorator pattern Evaluation techniques Object lifecycle hooks and method_missing Outline
  • 59. Hooks Allow you to trap some event, such as object creation… Example – adding a timestamp to every object created. (Taken from the pickaxe) class Object attr_accessor :timestamp end class Class alias_method :old_new, :new def new(*args) result = old_new(*args) result.timestamp = Time.now result end end
  • 60. Hooks You can know when a Module was included in another Object definition. module A def A.included(mod) puts &quot;#{self} included in #{mod}“ end end module Enumerable include A end This is done via a call to append_features on the module doing the including
  • 61. Hooks method_missing method_added method_removed You can hook into any of these and perform some operation when something happens to object under consideration. class Foo def method_missing(methodname, *args) #log something #handle in some way end end
  • 62. Hooks Can allow you to hook into how your plugins are intialized with Rails. Rails uses something called Rails::Plugin::Loader You can hook into this Rails::Initializer.run do |config| config.plugin_loader = PluginLoaderWithDependencies End Similarly, hooking into other framework type stuff (like ActiveRecord or even Subversion) is possible
  • 63. Metaprogramming with Ruby No longer black magic Fresh design patterns Declarative programming Higher level of abstraction Tone down the YAGNI
  翻译: