SlideShare a Scribd company logo
1 of 28
Download to read offline
Metaprogramming
Alex Koppel
6Wunderkinder

            Alex Koppel – 1/3/2012
What is
       metaprogramming?
!   "Like programming, only meta" – an old colleague

!   Code that writes code

!   "Metaprogramming is the writing of computer
   programs that write or manipulate other programs
   (or themselves) as their data, or that do part of the
   work at run time that would otherwise be done at
   compile time.“ – Wikipedia




                                    Alex Koppel - 6Wunderkinder
Why should you care?
!   Ruby allows metaprogramming

!   Metaprogramming can create stunningly
   effective tools
  !     Rails is metaprogramming

!   You want to be a more effective Ruby
   programmer




                                           6Wunderkinder
Caution!
!   Wield metaprogramming deliberately

!   Your code will be harder to understand
   !   Will other developers lose time figuring out your
       magic?

!   Your code will be more brittle
   !   Altering other classes = dependency
   !   Changes to underlying code can break your app
   !   c.f. Facebooker



                                              6Wunderkinder
Techniques




             6Wunderkinder
Reopening Classes
!   Add additional methods or variables to existing
   classes

!   Very simple, very powerful

!   New code is executed as your files are loaded
   !   In a sense, this is a "static" metaprogramming
   !   Common in monkeypatching

!   Caveat: this creates the class if not yet defined



                                             6Wunderkinder
Code
require 'active_support/core_ext/string/inflections'!

# reopen String class!
class String!
  # add a module!
  include ActiveSupport::CoreExtensions::String::Inflections!
end!




                                              6Wunderkinder
alias_method
!   alias_method(new_name, old_name)

!   Makes an copy of a method
   !   exist v. exists

!   Copy remains if the original is overridden
   !   You may remember alias_method_chain

!   Can be used dynamically in other methods




                                           6Wunderkinder
class Foo!
                   Code
  def bar!
     3!
  end!
  # make a copy of bar!
  alias_method :bar, :old_bar!
  # redefine bar!
  def bar!
     4!
  end!
end!

Foo.new.bar!
# => 4!
Foo.new.old_bar!
# => 3!                          6Wunderkinder
Metaclasses
!   All Ruby objects have a unique class
   !   The "metaclass", a.k.a. "eigenclass"
   !   Classes too
   !   Special cases: Fixnums, true, false, nil

!   You can access this class to change the object
   !   class << object opens up the metaclass
   !   def object.new_method and object.instance_eval
      also work

!   Note: reopening classes and alias_method alter
   the original class, not a metaclass
                                              6Wunderkinder
What are Objects and
                         Classes, really?
        !   An object is actually simple[1]
               !   A collection of instance variables
               !   A reference to a class

        !   When you call a method, Ruby goes up the class
               hierarchy for its definition
               !   Metaclass, then class, then superclass

        !   Changing methods on an individual object is
               really changing its metaclass


[1] http://ruby-doc.org/docs/ProgrammingRuby/html/classes.html   6Wunderkinder
Code 1: Classes
# Using class << self for a class is effectively!
# equivalent to reopening the class (see above)!
class Person!
! # this can be easier than writing tons of def self.s !
  class << self!
     def species!
       "Homo Sapien"!
     end!
  end!
end!

class << Person!
  def species; "Homo Sapien“; end!
end!

Person.species == “Homo Sapien“ # true!   6Wunderkinder
Code 2: Objects
str = "hello world"!
class << str!
  def foo!
     2!
  end!
end!

str.foo!
# => 2!
"hello world".foo!
# => NoMethodError!




                       6Wunderkinder
Case study: non-breaking changes

!   Example from Koala (Facebook SDK)

!   Changing a method to return strings rather than
   hashes

!   Could this be done without breaking apps?

!   Use metaprogramming on the returned strings
   !   Add missing methods
   !   Print deprecation warning




                                         6Wunderkinder
Code
def get_app_access_token!
  info = get_app_access_token_info # hash!
  string = info["access_token"]!

  # make the string compatible with hash accessors!
  command = <<-EOS!
    def [](index)!
       puts "DEPRECATION WARNING"!
       hash = #{hash.inspect} !
       hash[index]!
    end!
  EOS!

  # add those methods just to the string!
  (class << string; self; end).class_eval command!
end!
                                       6Wunderkinder
How does it work?
!   Get the individual string's metaclass:
    !   (class << str; self; end)
    !   Opens the class scope, and returns the (meta)class

!   class_eval
    !   Executes code in the scope of a class (or metaclass)
    !   class_eval requires a class, not an instance
    !   String eval can be used for dynamic content
    !   You can also eval a regular code block

!   Objects altered like this are "singletons"
    !   Has runtime implications



                                                 6Wunderkinder
Problem!
!   Ruby's Marshal.dump is used to serialize objects

!   Marshaling does NOT work with singletons
   !   Singletons can't be cached!

!   Defining instance#_dump doesn't help
   !   Expects String#load to exist

!   Use this carefully in shared code
   !   You never know what your users will do




                                           6Wunderkinder
Solution!
!   Use modules to mix in unique methods
    !   Ruby knows how to handle this, even for objects
module BackwardsCompatible!
  def [](key)!
     puts "Got key! #{key}"!
  end!
end!

my_string = "abc”!
# objects:extend <=> classes:include !
my_string.send(:extend, BackwardsCompatible)!
my_string["foo"]!
Got key! foo!
 => nil !
Marshal.dump(my_string)!
 => "x04bIe:x18BackwardsCompatible"babcx06:x06ET" !
                                           6Wunderkinder
class_eval again
!   Ruby pattern: modules updating the including class
   !   Add before_filters, attrs, etc.
   !   Could use .send in some cases
       !   class_eval is easier to read
   !   Can define dynamic methods
   !   ActiveSupport::Concern works this way

!   class_eval is like reopening a class
   !   But can be used without knowing the class in advance
   !   Won't create the class if it doesn't exist


                                                6Wunderkinder
Code
module ControllerStuff!
  def self.included(base)!
     # execute new code in the scope of!
     # the including class!
     base.class_eval do!
       before_filter :module_method!
       attr_accessor :module_var!
       @module_var = 2!
     end!
  end!
end!


                               6Wunderkinder
Method Missing
!   Intercept calls to non-existent methods

!   Make a class's interface dynamic

!   Example: ActiveRecord
    !   Create dynamic finders on the fly
   !   @user.find_by_name_and_status

!   Example: proxy objects




                                            6Wunderkinder
Pseudo-code for
           ActiveRecord 2.x
def method_missing(method_id, *args, &block)!
  # is it the right find_by_...format?!
! if match(method_id) && match.finder?!
!    # method_missing is a class method !
    self.class_eval %{ # string!
       # define the method!
       def self.#{method_id}(*args)!
         find(:#{finder}, options.merge    !
            (finder_options))!
       end!
    end!
    # now call the new method!
    send(method_id, *arguments)!
  end!
end       !
                                       6Wunderkinder
Important Note
    !   method_missing can be much slower

    !   There are some tricky issues
           !   respond_to? and beyond
           !   Solving each problem can create others [1]

    !   Don't overuse it
           !   Can you use define_method instead?




[1] http://www.slideshare.net/paoloperrotta/the-revenge-of-methodmissing   6Wunderkinder
Reaching into Objects
!   send: call any method on an object (public or not)
   !   Useful for dynamic programming
   !   Can also be used to break encapsulation
   !   public_send (1.9) is safer

!   instance_variable_get, instance_variable_set:
   !   Access variables that lack an accessor
   !   Don't use these




                                            6Wunderkinder
Code
# from Koala (older)!
# Scope: class with Typhoeous module included!

def self.make_request(path, args, verb)!
    # dynamically call the appropriate method!
    # corresponding to the verb requested !
!   self.send(verb, url, :params => args)!
End!

# from Rails!
# Scope: a helper class that needs a !
#        private controller method!

def universal_calculation(arg)!
  # call the method on the controller!
  controller.send(:universal_controller, arg)!
end !                             6Wunderkinder
tl;dr
!   Metaprogramming is awesome

!   Don’t overuse it
   !   But don’t be afraid to use it when appropriate

!   Enjoy :)




                                             6Wunderkinder
Resources
!   Ruby books

!   URLs:
    !   http://yehudakatz.com/2009/11/15/metaprogramming-
        in-ruby-its-all-about-the-self/
    !   http://ruby-doc.org/docs/ProgrammingRuby/html/
        classes.html
    !   http://www.slideshare.net/paoloperrotta/the-
       revenge-of-methodmissing
   !   http://pragprog.com/book/ppmetr/metaprogramming-
       ruby

!   Google "ruby metaprogramming“


                                              6Wunderkinder
Questions?
  @arsduo
@6Wunderkinder




                 6Wunderkinder

More Related Content

What's hot

Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming languageMarco Cedaro
 
Unbreaking Your Django Application
Unbreaking Your Django ApplicationUnbreaking Your Django Application
Unbreaking Your Django ApplicationOSCON Byrum
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2Usman Mehmood
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 

What's hot (11)

Paris Web - Javascript as a programming language
Paris Web - Javascript as a programming languageParis Web - Javascript as a programming language
Paris Web - Javascript as a programming language
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Unbreaking Your Django Application
Unbreaking Your Django ApplicationUnbreaking Your Django Application
Unbreaking Your Django Application
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
ClassJS
ClassJSClassJS
ClassJS
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 

Viewers also liked

Government Mobile Marketing Guide
Government Mobile Marketing GuideGovernment Mobile Marketing Guide
Government Mobile Marketing GuideWaterfall Mobile
 
Сгореть на работе и восстать из пепла (SQA Days-15)
Сгореть на работе и восстать из пепла (SQA Days-15)Сгореть на работе и восстать из пепла (SQA Days-15)
Сгореть на работе и восстать из пепла (SQA Days-15)Catherine Tipanova
 
Individuals with disabilities in higher education
Individuals with disabilities in higher educationIndividuals with disabilities in higher education
Individuals with disabilities in higher educationSusan Moore
 
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)Catherine Tipanova
 
Krimp: opgave en uitdaging
Krimp: opgave en uitdagingKrimp: opgave en uitdaging
Krimp: opgave en uitdagingbuitenhek
 
Fall sem 2010 exam set #3
Fall sem 2010 exam set #3Fall sem 2010 exam set #3
Fall sem 2010 exam set #3tracygrem
 
Seeds Of Greatness
Seeds Of GreatnessSeeds Of Greatness
Seeds Of Greatnessmjandmichael
 
ניהול זמנים פסיכומטרי בפרק הכמותי
ניהול זמנים פסיכומטרי בפרק הכמותיניהול זמנים פסיכומטרי בפרק הכמותי
ניהול זמנים פסיכומטרי בפרק הכמותיKidum LTD
 
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 42011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4Utah Division of Wildlife Resources
 
Understanding the misconception
Understanding the misconceptionUnderstanding the misconception
Understanding the misconceptionleondorsey1986
 

Viewers also liked (20)

Government Mobile Marketing Guide
Government Mobile Marketing GuideGovernment Mobile Marketing Guide
Government Mobile Marketing Guide
 
Presentacio1
Presentacio1Presentacio1
Presentacio1
 
Сгореть на работе и восстать из пепла (SQA Days-15)
Сгореть на работе и восстать из пепла (SQA Days-15)Сгореть на работе и восстать из пепла (SQA Days-15)
Сгореть на работе и восстать из пепла (SQA Days-15)
 
Individuals with disabilities in higher education
Individuals with disabilities in higher educationIndividuals with disabilities in higher education
Individuals with disabilities in higher education
 
Silver
SilverSilver
Silver
 
It og medier.
It og medier. It og medier.
It og medier.
 
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)
Жизненный цикл тестировщика (Урансофт, семинар TrueTester #3)
 
Jumlah ma di ntb
Jumlah ma di ntbJumlah ma di ntb
Jumlah ma di ntb
 
Krimp: opgave en uitdaging
Krimp: opgave en uitdagingKrimp: opgave en uitdaging
Krimp: opgave en uitdaging
 
Vocabulari
VocabulariVocabulari
Vocabulari
 
Epidermis
EpidermisEpidermis
Epidermis
 
Jasmine soap
Jasmine soapJasmine soap
Jasmine soap
 
Fall sem 2010 exam set #3
Fall sem 2010 exam set #3Fall sem 2010 exam set #3
Fall sem 2010 exam set #3
 
Pdr v2
Pdr v2Pdr v2
Pdr v2
 
Seeds Of Greatness
Seeds Of GreatnessSeeds Of Greatness
Seeds Of Greatness
 
ניהול זמנים פסיכומטרי בפרק הכמותי
ניהול זמנים פסיכומטרי בפרק הכמותיניהול זמנים פסיכומטרי בפרק הכמותי
ניהול זמנים פסיכומטרי בפרק הכמותי
 
START2GO: LevelUp
START2GO: LevelUpSTART2GO: LevelUp
START2GO: LevelUp
 
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 42011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4
2011 Bucks, Bulls and Once-in-a-Lifetime Permit Number Recommendations, May 4
 
Acid rain
Acid rainAcid rain
Acid rain
 
Understanding the misconception
Understanding the misconceptionUnderstanding the misconception
Understanding the misconception
 

Similar to Metaprogramming

Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patternsJeremy Duvall
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming RailsJustus Eapen
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Codeeddiehaber
 
JavaScripts internals #1
JavaScripts internals #1JavaScripts internals #1
JavaScripts internals #1Martin Pernica
 
Building reusable components with generics and protocols
Building reusable components with generics and protocolsBuilding reusable components with generics and protocols
Building reusable components with generics and protocolsDonny Wals
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
The Black Magic of Ruby Metaprogramming
The Black Magic of Ruby MetaprogrammingThe Black Magic of Ruby Metaprogramming
The Black Magic of Ruby Metaprogrammingitnig
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gemsliahhansen
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.pptSeethaDinesh
 
Learning PHP for Drupal Theming, DC Chicago 2009
Learning PHP for Drupal Theming, DC Chicago 2009Learning PHP for Drupal Theming, DC Chicago 2009
Learning PHP for Drupal Theming, DC Chicago 2009Emma Jane Hogbin Westby
 

Similar to Metaprogramming (20)

Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Oop in php_tutorial
Oop in php_tutorialOop in php_tutorial
Oop in php_tutorial
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
JavaScripts internals #1
JavaScripts internals #1JavaScripts internals #1
JavaScripts internals #1
 
Building reusable components with generics and protocols
Building reusable components with generics and protocolsBuilding reusable components with generics and protocols
Building reusable components with generics and protocols
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
inheritance
inheritanceinheritance
inheritance
 
The Black Magic of Ruby Metaprogramming
The Black Magic of Ruby MetaprogrammingThe Black Magic of Ruby Metaprogramming
The Black Magic of Ruby Metaprogramming
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Deciphering the Ruby Object Model
Deciphering the Ruby Object ModelDeciphering the Ruby Object Model
Deciphering the Ruby Object Model
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gems
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
 
Learning PHP for Drupal Theming, DC Chicago 2009
Learning PHP for Drupal Theming, DC Chicago 2009Learning PHP for Drupal Theming, DC Chicago 2009
Learning PHP for Drupal Theming, DC Chicago 2009
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 

Recently uploaded

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Metaprogramming

  • 1. Metaprogramming Alex Koppel 6Wunderkinder Alex Koppel – 1/3/2012
  • 2. What is metaprogramming? !   "Like programming, only meta" – an old colleague !   Code that writes code !   "Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at run time that would otherwise be done at compile time.“ – Wikipedia Alex Koppel - 6Wunderkinder
  • 3. Why should you care? !   Ruby allows metaprogramming !   Metaprogramming can create stunningly effective tools !   Rails is metaprogramming !   You want to be a more effective Ruby programmer 6Wunderkinder
  • 4. Caution! !   Wield metaprogramming deliberately !   Your code will be harder to understand !   Will other developers lose time figuring out your magic? !   Your code will be more brittle !   Altering other classes = dependency !   Changes to underlying code can break your app !   c.f. Facebooker 6Wunderkinder
  • 5. Techniques 6Wunderkinder
  • 6. Reopening Classes !   Add additional methods or variables to existing classes !   Very simple, very powerful !   New code is executed as your files are loaded !   In a sense, this is a "static" metaprogramming !   Common in monkeypatching !   Caveat: this creates the class if not yet defined 6Wunderkinder
  • 7. Code require 'active_support/core_ext/string/inflections'! # reopen String class! class String! # add a module! include ActiveSupport::CoreExtensions::String::Inflections! end! 6Wunderkinder
  • 8. alias_method !   alias_method(new_name, old_name) !   Makes an copy of a method !   exist v. exists !   Copy remains if the original is overridden !   You may remember alias_method_chain !   Can be used dynamically in other methods 6Wunderkinder
  • 9. class Foo! Code def bar! 3! end! # make a copy of bar! alias_method :bar, :old_bar! # redefine bar! def bar! 4! end! end! Foo.new.bar! # => 4! Foo.new.old_bar! # => 3! 6Wunderkinder
  • 10. Metaclasses !   All Ruby objects have a unique class !   The "metaclass", a.k.a. "eigenclass" !   Classes too !   Special cases: Fixnums, true, false, nil !   You can access this class to change the object !   class << object opens up the metaclass !   def object.new_method and object.instance_eval also work !   Note: reopening classes and alias_method alter the original class, not a metaclass 6Wunderkinder
  • 11. What are Objects and Classes, really? !   An object is actually simple[1] !   A collection of instance variables !   A reference to a class !   When you call a method, Ruby goes up the class hierarchy for its definition !   Metaclass, then class, then superclass !   Changing methods on an individual object is really changing its metaclass [1] http://ruby-doc.org/docs/ProgrammingRuby/html/classes.html 6Wunderkinder
  • 12. Code 1: Classes # Using class << self for a class is effectively! # equivalent to reopening the class (see above)! class Person! ! # this can be easier than writing tons of def self.s ! class << self! def species! "Homo Sapien"! end! end! end! class << Person! def species; "Homo Sapien“; end! end! Person.species == “Homo Sapien“ # true! 6Wunderkinder
  • 13. Code 2: Objects str = "hello world"! class << str! def foo! 2! end! end! str.foo! # => 2! "hello world".foo! # => NoMethodError! 6Wunderkinder
  • 14. Case study: non-breaking changes !   Example from Koala (Facebook SDK) !   Changing a method to return strings rather than hashes !   Could this be done without breaking apps? !   Use metaprogramming on the returned strings !   Add missing methods !   Print deprecation warning 6Wunderkinder
  • 15. Code def get_app_access_token! info = get_app_access_token_info # hash! string = info["access_token"]! # make the string compatible with hash accessors! command = <<-EOS! def [](index)! puts "DEPRECATION WARNING"! hash = #{hash.inspect} ! hash[index]! end! EOS! # add those methods just to the string! (class << string; self; end).class_eval command! end! 6Wunderkinder
  • 16. How does it work? !   Get the individual string's metaclass: !   (class << str; self; end) !   Opens the class scope, and returns the (meta)class !   class_eval !   Executes code in the scope of a class (or metaclass) !   class_eval requires a class, not an instance !   String eval can be used for dynamic content !   You can also eval a regular code block !   Objects altered like this are "singletons" !   Has runtime implications 6Wunderkinder
  • 17. Problem! !   Ruby's Marshal.dump is used to serialize objects !   Marshaling does NOT work with singletons !   Singletons can't be cached! !   Defining instance#_dump doesn't help !   Expects String#load to exist !   Use this carefully in shared code !   You never know what your users will do 6Wunderkinder
  • 18. Solution! !   Use modules to mix in unique methods !   Ruby knows how to handle this, even for objects module BackwardsCompatible! def [](key)! puts "Got key! #{key}"! end! end! my_string = "abc”! # objects:extend <=> classes:include ! my_string.send(:extend, BackwardsCompatible)! my_string["foo"]! Got key! foo! => nil ! Marshal.dump(my_string)! => "x04bIe:x18BackwardsCompatible"babcx06:x06ET" ! 6Wunderkinder
  • 19. class_eval again !   Ruby pattern: modules updating the including class !   Add before_filters, attrs, etc. !   Could use .send in some cases !   class_eval is easier to read !   Can define dynamic methods !   ActiveSupport::Concern works this way !   class_eval is like reopening a class !   But can be used without knowing the class in advance !   Won't create the class if it doesn't exist 6Wunderkinder
  • 20. Code module ControllerStuff! def self.included(base)! # execute new code in the scope of! # the including class! base.class_eval do! before_filter :module_method! attr_accessor :module_var! @module_var = 2! end! end! end! 6Wunderkinder
  • 21. Method Missing !   Intercept calls to non-existent methods !   Make a class's interface dynamic !   Example: ActiveRecord !   Create dynamic finders on the fly !   @user.find_by_name_and_status !   Example: proxy objects 6Wunderkinder
  • 22. Pseudo-code for ActiveRecord 2.x def method_missing(method_id, *args, &block)! # is it the right find_by_...format?! ! if match(method_id) && match.finder?! ! # method_missing is a class method ! self.class_eval %{ # string! # define the method! def self.#{method_id}(*args)! find(:#{finder}, options.merge ! (finder_options))! end! end! # now call the new method! send(method_id, *arguments)! end! end ! 6Wunderkinder
  • 23. Important Note !   method_missing can be much slower !   There are some tricky issues !   respond_to? and beyond !   Solving each problem can create others [1] !   Don't overuse it !   Can you use define_method instead? [1] http://www.slideshare.net/paoloperrotta/the-revenge-of-methodmissing 6Wunderkinder
  • 24. Reaching into Objects !   send: call any method on an object (public or not) !   Useful for dynamic programming !   Can also be used to break encapsulation !   public_send (1.9) is safer !   instance_variable_get, instance_variable_set: !   Access variables that lack an accessor !   Don't use these 6Wunderkinder
  • 25. Code # from Koala (older)! # Scope: class with Typhoeous module included! def self.make_request(path, args, verb)! # dynamically call the appropriate method! # corresponding to the verb requested ! ! self.send(verb, url, :params => args)! End! # from Rails! # Scope: a helper class that needs a ! # private controller method! def universal_calculation(arg)! # call the method on the controller! controller.send(:universal_controller, arg)! end ! 6Wunderkinder
  • 26. tl;dr !   Metaprogramming is awesome !   Don’t overuse it !   But don’t be afraid to use it when appropriate !   Enjoy :) 6Wunderkinder
  • 27. Resources !   Ruby books !   URLs: !   http://yehudakatz.com/2009/11/15/metaprogramming- in-ruby-its-all-about-the-self/ !   http://ruby-doc.org/docs/ProgrammingRuby/html/ classes.html !   http://www.slideshare.net/paoloperrotta/the- revenge-of-methodmissing !   http://pragprog.com/book/ppmetr/metaprogramming- ruby !   Google "ruby metaprogramming“ 6Wunderkinder