SlideShare una empresa de Scribd logo
1 de 74
Descargar para leer sin conexión
metaprogramming
        +
     domain
     specific
   languages
%  cat  ddfreyne.txt

DENIS  DEFREYNE
==============

web:          http://stoneship.org
twitter:  ddfreyne

nanoc:  a  static  ruby  web  site  publishing  system
http://nanoc.stoneship.org/

%  _
what is
metaprogramming?
Metaprogramming is the
   writing of computer
 programs that write or
    manipulate other
programs (or themselves)
       as their data.
class  Person

    attr_reader  :friends

end
class  Document  <  ActiveRecord::Base

    has_many  :pages

end
task  :test  do
    puts  "Hello,  I  am  a  rake  task!"
end
example (i)
class  Bob
    my_attr_reader  :foo,  :bar
end
class  Module

    def  my_attr_reader(*fields)
        fields.each  do  |field|

            class_eval  "
                def  #{field}
                    @#{field}
                end
            "

        end
    end

end
class  Module

    def  my_attr_reader(*fields)
        fields.each  do  |field|

            class_eval  "
                def  #{field}
                    @#{field}
                end
            "

        end
    end

end
def  #{field}
    @#{field}
end
def  foo
    @foo
end
def  bar
    @bar
end
class  Module

    def  my_attr_reader(*fields)
        fields.each  do  |field|

            class_eval  "
                def  #{field}
                    @#{field}
                end
            "

        end
    end

end
DEMO
example (ii)
class  Module

    def  my_attr_reader(*fields)
        fields.each  do  |field|

            class_eval  "
                def  #{field}
                    @#{field}
                end
            "

        end
    end

end
class  Module

    def  battr_reader(*fields)
        fields.each  do  |field|

            class_eval  "
                def  #{field}?
                    !!@#{field}
                end
            "

        end
    end

end
class  Bob
    battr_reader  :foo,  :bar
end

p  bob.foo?
p  bob.bar?
DEMO
example (iii)
<p>Hello.  My  name  is  <%=  @first_name  %>.</p>
template  =  "<p>Hello.  My  name  is  <%=
    @first_name  %>.</p>"

@first_name  =  "Bob"

p  ERB.new(template).result
DEMO
example (iv)
class  Product
    def  initialize
        @title  =  "My  First  Ruby  Book"
        @id        =  "39t8zfeg"
    end
end

template  =  "<p>Product  <%=
    @id  %>  has  title  <%=  @title  %>.</p>"

product  =  Product.new

#  TODO  use  the  product  details  
p  ERB.new(template).result
class  Product
    def  initialize
        @title  =  "My  First  Ruby  Book"
        @id        =  "39t8zfeg"
    end

    def  print
        template  =  "<p>Product  <%=
            @id  %>  has  title  <%=  @title  %>.</p>"

        puts  ERB.new(template).result(binding)
    end
end
class  Product
    def  initialize
        @title  =  "My  First  Ruby  Book"
        @id        =  "39t8zfeg"
    end

    def  print
        template  =  "<p>Product  <%=
            @id  %>  has  title  <%=  @title  %>.</p>"

        puts  ERB.new(template).result(binding)
    end
end
class  Product

    def  initialize
        @title  =  "My  First  Ruby  Book"
        @id        =  "39t8zfeg"
    end




end
class  Product

    def  initialize
        @title  =  "My  First  Ruby  Book"
        @id        =  "39t8zfeg"
    end

    def  get_binding
        binding
    end

end
def  get_binding
    binding
end
def  get_binding
    binding
end
def  binding
    binding
end
def  binding
    binding
end

SystemStackError:  stack  level  too  deep
template  =  "<p>Product  <%=
    @id  %>  has  title  <%=  @title  %>.</p>"

product  =  Product.new

p  ERB.new(template).result
template  =  "<p>Product  <%=
    @id  %>  has  title  <%=  @title  %>.</p>"

product  =  Product.new

p  ERB.new(template).result(product.get_binding)
DEMO
example (v)
compile  '/articles/*/'  do
    filter  :erb
    filter  :bluecloth

    layout  'article'

    filter  :rubypants
end
my-­‐site/
    config.yaml
    Rules
    content/
    layouts/
    lib/
… simpler

process  /oo/  do  |item|
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
class  Item

    attr_reader  :identifier

    def  initialize(identifier)
        @identifier  =  identifier
    end

end
items  =  [
    Item.new('foo'),
    Item.new('foobar'),
    Item.new('quxbar'),
    Item.new('moo')
]

magically_load_rules

items.each  do  |item|
    magically_process(item)
end
class  Rule

    def  initialize(pattern,  block)
        @pattern  =  pattern
        @block      =  block
    end

    def  applicable_to?(item)
        item.identifier  =~  @pattern
    end

    def  apply_to(item)
        @block.call(item)
    end

end
class  Application

    def  initialize
        @rules  =  []
    end

    def  load_rules
        rules_content  =  File.read('Rules')
        dsl  =  DSL.new(@rules)
        dsl.instance_eval(rules_content)
    end

    ⋮
class  Application

    def  initialize
        @rules  =  []
    end

    def  load_rules
        rules_content  =  File.read('Rules')
        dsl  =  DSL.new(@rules)
        dsl.instance_eval(rules_content)
    end

    ⋮
class  Bob

    def  initialize
        @secret  =  "abc"
    end

end
bob  =  Bob.new
p  bob.secret

NoMethodError:  undefined  method  `secret'
    for  #<Bob:0x574324>
bob  =  Bob.new
p  bob.instance_eval  {  @secret  }

abc
bob  =  Bob.new
p  bob.instance_eval  "@secret"

abc
class  Application

    def  initialize
        @rules  =  []
    end

    def  load_rules
        rules_content  =  File.read('Rules')
        dsl  =  DSL.new(@rules)
        dsl.instance_eval(rules_content)
    end

    ⋮
   ⋮

    def  process(item)
        rule  =  rules.find  do  |r|
            r.applicable_to?(item)
        end

        rule.apply_to(item)
    end

end
class  DSL

    def  initialize(rules)
        @rules  =  rules
    end

    def  process(pattern,  &block)
        @rules  <<  Rule.new(pattern,  block)
    end

end
class  DSL

    def  initialize(rules)
        @rules  =  rules
    end

    def  process(pattern,  &block)
        @rules  <<  Rule.new(pattern,  block)
    end

end
process  /oo/  do  |item|
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
process  /oo/  do  |item|
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
items  =  [
    Item.new('foo'),
    Item.new('foobar'),
    Item.new('quxbar'),
    Item.new('moo')
]

app  =  App.new
app.load_rules

items.each  do  |item|
    app.process(item)
end
DEMO
example (vi)
process  /oo/  do  |item|
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
process  /oo/  do
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
class  RuleContext

    def  initialize(item)
        @item  =  item
    end

end
class  Rule

    def  initialize(pattern,  block)
        @pattern  =  pattern
        @block      =  block
    end

    def  applicable_to?(item)
        item.identifier  =~  @pattern
    end

    def  apply_to(item)
        #  original  way:
        @block.call(item)
    end

end
class  Rule

    def  initialize(pattern,  block)
        @pattern  =  pattern
        @block      =  block
    end

    def  applicable_to?(item)
        item.identifier  =~  @pattern
    end

    def  apply_to(item)
        rule_context  =  RuleContext.new(item)
        rule_context.instance_eval(&@block)
    end

end
process  /oo/  do
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{@item.inspect}!"
end
process  /oo/  do
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
class  RuleContext

    def  initialize(item)
        @item  =  item
    end




end
class  RuleContext

    def  initialize(item)
        @item  =  item
    end

    def  item
        @item
    end

end
process  /oo/  do
    puts  "I  am  rule  /oo/!"
    puts  "I  am  processing  #{item.inspect}!"
end
DEMO
‣ The Ruby Object Model
  and Metaprogramming
  http://www.pragprog.com/screencasts/v-
  dtrubyom/the-ruby-object-model-and-
  metaprogramming

‣ How nanocʼs Rules DSL Works
  http://stoneship.org/journal/2009/how-
  nanocs-rules-dsl-works/
you can haz
questions?
k thx bai

Más contenido relacionado

La actualidad más candente

LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
Michael Girouard
 

La actualidad más candente (17)

Any tutor
Any tutorAny tutor
Any tutor
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1
 
Javascript
JavascriptJavascript
Javascript
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented Programming
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
 
ORM in Django
ORM in DjangoORM in Django
ORM in Django
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 

Destacado

Ogc in arc_gis_g_tstyle
Ogc in arc_gis_g_tstyleOgc in arc_gis_g_tstyle
Ogc in arc_gis_g_tstyle
Gert-Jan
 
Oer slides fall 2013
Oer slides fall 2013Oer slides fall 2013
Oer slides fall 2013
WayneSmith
 
Iii jal pres_avaluaciocompetencial
Iii jal pres_avaluaciocompetencialIii jal pres_avaluaciocompetencial
Iii jal pres_avaluaciocompetencial
Arnau Cerdà
 
HOT N´COLD
HOT N´COLD HOT N´COLD
HOT N´COLD
Sonia
 
Digital Mediaina state
Digital Mediaina stateDigital Mediaina state
Digital Mediaina state
Sales Hub Pro
 

Destacado (20)

2011 some photos
2011 some photos2011 some photos
2011 some photos
 
Hoboes Expo2
Hoboes Expo2Hoboes Expo2
Hoboes Expo2
 
Ngc sepsis
Ngc sepsisNgc sepsis
Ngc sepsis
 
Candidiasis invasiva
Candidiasis invasivaCandidiasis invasiva
Candidiasis invasiva
 
Ogc in arc_gis_g_tstyle
Ogc in arc_gis_g_tstyleOgc in arc_gis_g_tstyle
Ogc in arc_gis_g_tstyle
 
¿Tratamiento antirretroviral como prevencion?
¿Tratamiento antirretroviral como prevencion?¿Tratamiento antirretroviral como prevencion?
¿Tratamiento antirretroviral como prevencion?
 
Tb XDR in South Africa
Tb XDR in South AfricaTb XDR in South Africa
Tb XDR in South Africa
 
Tomillo
TomilloTomillo
Tomillo
 
Oer slides fall 2013
Oer slides fall 2013Oer slides fall 2013
Oer slides fall 2013
 
Guida Ebooks & iBooks Author
Guida Ebooks & iBooks Author Guida Ebooks & iBooks Author
Guida Ebooks & iBooks Author
 
Geotrails
GeotrailsGeotrails
Geotrails
 
Pubcon 2013 - Post mortem banned site forensics
Pubcon 2013 - Post mortem  banned site forensicsPubcon 2013 - Post mortem  banned site forensics
Pubcon 2013 - Post mortem banned site forensics
 
Aftershock
AftershockAftershock
Aftershock
 
Iii jal pres_avaluaciocompetencial
Iii jal pres_avaluaciocompetencialIii jal pres_avaluaciocompetencial
Iii jal pres_avaluaciocompetencial
 
Smart Questions
Smart QuestionsSmart Questions
Smart Questions
 
Treeshed story
Treeshed storyTreeshed story
Treeshed story
 
How to run asp.net on virtual server for $5 per mo
How to run asp.net on  virtual server for $5 per moHow to run asp.net on  virtual server for $5 per mo
How to run asp.net on virtual server for $5 per mo
 
HOT N´COLD
HOT N´COLD HOT N´COLD
HOT N´COLD
 
Freelance Robotics Company Profile V1 2
Freelance Robotics Company Profile V1 2Freelance Robotics Company Profile V1 2
Freelance Robotics Company Profile V1 2
 
Digital Mediaina state
Digital Mediaina stateDigital Mediaina state
Digital Mediaina state
 

Similar a Metaprogramming + Ds Ls

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Key
guesta2b31d
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 

Similar a Metaprogramming + Ds Ls (20)

Ruby
RubyRuby
Ruby
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)Refactoring Workshop (Rails Pacific 2014)
Refactoring Workshop (Rails Pacific 2014)
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
Dsl
DslDsl
Dsl
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Presentation.Key
Presentation.KeyPresentation.Key
Presentation.Key
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 

Más de ArrrrCamp (15)

Arrrrcamp Radiant Intro
Arrrrcamp Radiant IntroArrrrcamp Radiant Intro
Arrrrcamp Radiant Intro
 
Ruby 1.9 And Rails 3.0
Ruby 1.9 And Rails 3.0Ruby 1.9 And Rails 3.0
Ruby 1.9 And Rails 3.0
 
Rubyandrails
RubyandrailsRubyandrails
Rubyandrails
 
Nanoc
NanocNanoc
Nanoc
 
Git
GitGit
Git
 
Radiant
RadiantRadiant
Radiant
 
Mistakes
MistakesMistakes
Mistakes
 
Railsservers
RailsserversRailsservers
Railsservers
 
Prawn
PrawnPrawn
Prawn
 
Testing
TestingTesting
Testing
 
Validation
ValidationValidation
Validation
 
Cucumber
CucumberCucumber
Cucumber
 
Ruby and Rails Basics
Ruby and Rails BasicsRuby and Rails Basics
Ruby and Rails Basics
 
Caching your rails application
Caching your rails applicationCaching your rails application
Caching your rails application
 
Advanced Radiant
Advanced RadiantAdvanced Radiant
Advanced Radiant
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Metaprogramming + Ds Ls

  • 1. metaprogramming + domain specific languages
  • 2. %  cat  ddfreyne.txt DENIS  DEFREYNE ============== web:          http://stoneship.org twitter:  ddfreyne nanoc:  a  static  ruby  web  site  publishing  system http://nanoc.stoneship.org/ %  _
  • 4. Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data.
  • 5. class  Person    attr_reader  :friends end
  • 6. class  Document  <  ActiveRecord::Base    has_many  :pages end
  • 7. task  :test  do    puts  "Hello,  I  am  a  rake  task!" end
  • 9. class  Bob    my_attr_reader  :foo,  :bar end
  • 10. class  Module    def  my_attr_reader(*fields)        fields.each  do  |field|            class_eval  "                def  #{field}                    @#{field}                end            "        end    end end
  • 11. class  Module    def  my_attr_reader(*fields)        fields.each  do  |field|            class_eval  "                def  #{field}                    @#{field}                end            "        end    end end
  • 12. def  #{field}    @#{field} end
  • 13. def  foo    @foo end
  • 14. def  bar    @bar end
  • 15. class  Module    def  my_attr_reader(*fields)        fields.each  do  |field|            class_eval  "                def  #{field}                    @#{field}                end            "        end    end end
  • 16. DEMO
  • 18. class  Module    def  my_attr_reader(*fields)        fields.each  do  |field|            class_eval  "                def  #{field}                    @#{field}                end            "        end    end end
  • 19. class  Module    def  battr_reader(*fields)        fields.each  do  |field|            class_eval  "                def  #{field}?                    !!@#{field}                end            "        end    end end
  • 20. class  Bob    battr_reader  :foo,  :bar end p  bob.foo? p  bob.bar?
  • 21. DEMO
  • 23. <p>Hello.  My  name  is  <%=  @first_name  %>.</p>
  • 24. template  =  "<p>Hello.  My  name  is  <%=    @first_name  %>.</p>" @first_name  =  "Bob" p  ERB.new(template).result
  • 25. DEMO
  • 27. class  Product    def  initialize        @title  =  "My  First  Ruby  Book"        @id        =  "39t8zfeg"    end end template  =  "<p>Product  <%=    @id  %>  has  title  <%=  @title  %>.</p>" product  =  Product.new #  TODO  use  the  product  details   p  ERB.new(template).result
  • 28. class  Product    def  initialize        @title  =  "My  First  Ruby  Book"        @id        =  "39t8zfeg"    end    def  print        template  =  "<p>Product  <%=            @id  %>  has  title  <%=  @title  %>.</p>"        puts  ERB.new(template).result(binding)    end end
  • 29. class  Product    def  initialize        @title  =  "My  First  Ruby  Book"        @id        =  "39t8zfeg"    end    def  print        template  =  "<p>Product  <%=            @id  %>  has  title  <%=  @title  %>.</p>"        puts  ERB.new(template).result(binding)    end end
  • 30. class  Product    def  initialize        @title  =  "My  First  Ruby  Book"        @id        =  "39t8zfeg"    end end
  • 31. class  Product    def  initialize        @title  =  "My  First  Ruby  Book"        @id        =  "39t8zfeg"    end    def  get_binding        binding    end end
  • 32. def  get_binding    binding end
  • 33. def  get_binding    binding end
  • 34. def  binding    binding end
  • 35. def  binding    binding end SystemStackError:  stack  level  too  deep
  • 36. template  =  "<p>Product  <%=    @id  %>  has  title  <%=  @title  %>.</p>" product  =  Product.new p  ERB.new(template).result
  • 37. template  =  "<p>Product  <%=    @id  %>  has  title  <%=  @title  %>.</p>" product  =  Product.new p  ERB.new(template).result(product.get_binding)
  • 38. DEMO
  • 40. compile  '/articles/*/'  do    filter  :erb    filter  :bluecloth    layout  'article'    filter  :rubypants end
  • 41. my-­‐site/    config.yaml    Rules    content/    layouts/    lib/
  • 42. … simpler process  /oo/  do  |item|    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 43. class  Item    attr_reader  :identifier    def  initialize(identifier)        @identifier  =  identifier    end end
  • 44. items  =  [    Item.new('foo'),    Item.new('foobar'),    Item.new('quxbar'),    Item.new('moo') ] magically_load_rules items.each  do  |item|    magically_process(item) end
  • 45. class  Rule    def  initialize(pattern,  block)        @pattern  =  pattern        @block      =  block    end    def  applicable_to?(item)        item.identifier  =~  @pattern    end    def  apply_to(item)        @block.call(item)    end end
  • 46. class  Application    def  initialize        @rules  =  []    end    def  load_rules        rules_content  =  File.read('Rules')        dsl  =  DSL.new(@rules)        dsl.instance_eval(rules_content)    end    ⋮
  • 47. class  Application    def  initialize        @rules  =  []    end    def  load_rules        rules_content  =  File.read('Rules')        dsl  =  DSL.new(@rules)        dsl.instance_eval(rules_content)    end    ⋮
  • 48. class  Bob    def  initialize        @secret  =  "abc"    end end
  • 49. bob  =  Bob.new p  bob.secret NoMethodError:  undefined  method  `secret'    for  #<Bob:0x574324>
  • 50. bob  =  Bob.new p  bob.instance_eval  {  @secret  } abc
  • 51. bob  =  Bob.new p  bob.instance_eval  "@secret" abc
  • 52. class  Application    def  initialize        @rules  =  []    end    def  load_rules        rules_content  =  File.read('Rules')        dsl  =  DSL.new(@rules)        dsl.instance_eval(rules_content)    end    ⋮
  • 53.    ⋮    def  process(item)        rule  =  rules.find  do  |r|            r.applicable_to?(item)        end        rule.apply_to(item)    end end
  • 54. class  DSL    def  initialize(rules)        @rules  =  rules    end    def  process(pattern,  &block)        @rules  <<  Rule.new(pattern,  block)    end end
  • 55. class  DSL    def  initialize(rules)        @rules  =  rules    end    def  process(pattern,  &block)        @rules  <<  Rule.new(pattern,  block)    end end
  • 56. process  /oo/  do  |item|    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 57. process  /oo/  do  |item|    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 58. items  =  [    Item.new('foo'),    Item.new('foobar'),    Item.new('quxbar'),    Item.new('moo') ] app  =  App.new app.load_rules items.each  do  |item|    app.process(item) end
  • 59. DEMO
  • 61. process  /oo/  do  |item|    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 62. process  /oo/  do    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 63. class  RuleContext    def  initialize(item)        @item  =  item    end end
  • 64. class  Rule    def  initialize(pattern,  block)        @pattern  =  pattern        @block      =  block    end    def  applicable_to?(item)        item.identifier  =~  @pattern    end    def  apply_to(item)        #  original  way:        @block.call(item)    end end
  • 65. class  Rule    def  initialize(pattern,  block)        @pattern  =  pattern        @block      =  block    end    def  applicable_to?(item)        item.identifier  =~  @pattern    end    def  apply_to(item)        rule_context  =  RuleContext.new(item)        rule_context.instance_eval(&@block)    end end
  • 66. process  /oo/  do    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{@item.inspect}!" end
  • 67. process  /oo/  do    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 68. class  RuleContext    def  initialize(item)        @item  =  item    end end
  • 69. class  RuleContext    def  initialize(item)        @item  =  item    end    def  item        @item    end end
  • 70. process  /oo/  do    puts  "I  am  rule  /oo/!"    puts  "I  am  processing  #{item.inspect}!" end
  • 71. DEMO
  • 72. ‣ The Ruby Object Model and Metaprogramming http://www.pragprog.com/screencasts/v- dtrubyom/the-ruby-object-model-and- metaprogramming ‣ How nanocʼs Rules DSL Works http://stoneship.org/journal/2009/how- nanocs-rules-dsl-works/