SlideShare uma empresa Scribd logo
1 de 48
DYNAMIC RUBY FOR NUBIES



                                   Nuby Hoedown MMX
                                   September 2nd, 2010




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
LANGUAGE




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
WHAT IS A DSL?



  • Domain-Specific              Language




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
CUCUMBER IS A DSL
    Feature: Password recovery
    As a forgetful user
    I want to be able to recover my password
    So that I can get back into the site when I lose my password!

    Scenario: Recovering password
       Given I have signed up as a user
        When I go to the home page
         And I click "Recover your password"
         And I fill in "Email" with "user@example.com"
         And my email address is "user@example.com"
         And I press "Reset my password"
        Then I should receive an email
        When I open the email
         And I click the first link in the email
         And I fill in "Password" with "simpsonsrock!"
         And I fill in "Password Confirmation" with "simpsonsrock!"
         And I press "Update password"
        Then I should be on the dashboard page
         And I should see "Your password has been reset"




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
REAL LANGUAGES


  • Rule-based

  • Pattern-matching

  • Very     dull to read




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION (RUBY)



  • Example: turn          the monitor background color green




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION (RUBY)




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION (RUBY)




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION (RUBY)


  • English: turn       the monitor background color green

  • Ruby: turn(“monitor”, “background”, “#00FF00”)




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION (RUBY)


  • Example: turn          the monitor background color green

  • Ruby: turn(        the( monitor( background( color( green) ) ) ) )




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
               turn the monitor background color green

   class DSLObject
     
     def method_missing(name,*args)
       return name.to_s
     end

   end

   # @dsl_object.green => "green"


Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
           turn the monitor background color “green”
   class DSLObject

     def color(name)
       case name
         when "green"             : "#00FF00"
         when "blue"              : "#0000FF"
         when "red"               : "#FF0000"
       end
     end
     
     def method_missing(name,*args)
       return name.to_s
     end

   end

   # @dsl_object.color green => NameError: undefined local variable
   or method `green' for #<Object:0x1001c8288>



Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
PROBLEM!

  • How      do we execute the code inside this object?

  • @dsl_object.color                     green

  • “green” is  evaluated within the current scope, so unless it’s a
    variable, it doesn’t exist

  • (what      we really mean is @dsl_object.color @dsl_object.green)



Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
LANGUAGE




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
BAD OBJECT-ORIENTATION




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
BETTER OBJECT-ORIENTATION




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
STATIC DISPATCH




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DYNAMIC DISPATCH




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
CONTEXT-SWITCHING




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
RUBY HAS DYNAMIC DISPATCH


  • Ruby     uses message-passing

  • @dsl_object.send(“col
    or green”)

  • Hey, some   guy named Irb
    says “color green”




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
WRONG AGAIN!
  • Hmmm, do   I have a method
    named “color green”? Nope

  • Do my ancestors have a
    method “color green”?
    Nope

  • Ooh! I’ll call
    method_missing(“color
    green”)

  • @dsl_object.send(“col
    or green”) #=> “color
Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
CHANGING SCOPE
     @dsl_object.instance_eval do
       # Everything in this block
       # will treat @dsl_object
       # as self

       color green
     end

     # This is equivalent
     @dsl_object.instance_eval("color green")



Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
           turn the monitor background “#00FF00”
class DSLObject

  def color(*args)
    case args[0]
      when "green"   then "#00FF00"
      when "blue"    then "#0000FF"
      when "red"     then "#FF0000"
    end
  end
  
  def method_missing(name,*args)
    return *args.flatten.unshift(name.to_s)
  end
end

# @dsl_object.instance_eval("background color green") =>
["background","#00FF00"]




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
      turn the monitor [“background”, “#00FF00”]
class DSLObject

  def color(*args)
    case args[0]
      when "green" then "#00FF00"
      when "blue"   then "#0000FF"
      when "red"    then "#FF0000"
    end
  end
  
  def method_missing(name,*args)
    return *args.flatten.unshift(name.to_s)
  end

end

# @dsl_object.instance_eval("monitor background color green") =>
["monitor","background","#00FF00"]




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
        turn the [“monitor”,“background”, “#00FF00”]
class DSLObject

  def color(*args)
    case args[0]
      when "green"   then "#00FF00"
      when "blue"    then "#0000FF"
      when "red"     then "#FF0000"
    end
  end

  def the(*args)
    return *args
  end
  
  def method_missing(name,*args)
    return *args.flatten.unshift(name.to_s)
  end

end

# @dsl_object.instance_eval("the monitor background color green") =>
["monitor","background","#00FF00"]


Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DSL EVALUATION
           turn [“monitor”,“background”, “#00FF00”]




              Now we’re in normal programming territory




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
CONTRIVED EXAMPLES


  • Example: turn          the beat around

  • With      our DSL #=> turn [“beat”,“around”]

  • Valid    syntax, bad semantics




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
SYNTAX LIMITATIONS


  • Example: Set          course for the Hoth system

  • Can     this be valid syntax?




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
SYNTAX LIMITATIONS

  • Example: Set          course for the Hoth system

  • Set, Hoth       => Constant undefined

  • for   => reserved word

  • system      => already defined (inherited from Object)




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
BLANK SLATE
  class DSLObject < BasicObject

    def method_missing(name,*args)
      return *args.flatten.unshift(name.to_s)
    end

    def const_missing(name)
      eval(name.to_s_downcase)
    end

  end

  # @dsl_object.instance_eval("Set course fer the Hoth system")
  #   => ["Set","course","fer","the","Hoth","system"]




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
TEXT ADVENTURE GAMES




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
DOCUMENTATION




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
LANGUAGE




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
ENVIRONMENTS ARE HARD
     game        = TextAdventureGame.new("My First Text Adventure")

     hallway = Location.new("A dark and quiet hallway")
     kitchen = Location.new("An abandoned kitchen")
     hall    = Location.new("A banquet hall...strangely
     deserted")

     game.rooms << hallway
     game.rooms << kitchen
     game.rooms << hall

     hallway.north = kitchen
     kitchen.south = hallway

     kitchen.north = hall
     hall.south    = kitchen




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
TEXT ADVENTURE WITH BLOCKS
         World.new("My First Text Adventure") do
           
           location "hallway" do
             description "A dark and quiet hallway"
             north       "kitchen"
           end

           location "kitchen" do
             description "An abandoned kitchen"
             south       "hallway"
           end

           start "hallway"

         end




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
PYTHONY TEXT ADVENTURE

         world "My First Text Adventure"
           
           location "hallway"
             description "A dark and quiet hallway"
             north       "kitchen"

           location "kitchen"
             description "An abandoned kitchen"
             south       "hallway"

           start "hallway"




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
INTERPRETATION




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
BLOCKS

  • do..end

  • Delayed        execution

  • Changes        the execution scope

  • Is   a real argument




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
CONTEXTS


  • instance_eval

  • class_eval

  • eval




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
WORLD
       require 'game'

       class World

         attr_accessor :name, :locations, :player

         def initialize(name,&block)
           @name       = name
           @locations = {}
           @player     = Player.new

           instance_eval &block
         end

         def location(name,&block)
           @locations[name] = Location.new(name,&block)
         end

         def start(location)
           @player.location = @locations[location]
         end

       end


Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
LOCATION
      class Location

        attr_accessor :name, :description, :exits

        def initialize(name,&block)
          @name       = name
          @exits      = {}

          instance_eval &block
        end

        def description(prose)
          @description = prose
        end

        ["north","south","east","west"].each do |direction|
          class_eval <<-END
            def #{direction}(location)
              @exits["#{direction}"] = location
            end
          END
        end

      end

Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
PLAYER
      class Player

        attr_accessor :location

      end




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
HANDLING USER INPUT


  • Preprocess         the input

  • Provide       a context to execute

  • Manipulate         the environment




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
PREPROCESS THE INPUT
      require   'world'
      require   'location'
      require   'player'
      require   'runner'

      class Game

        def self.run(world)
          runner = Runner.new(world)
          puts "Welcome to the text adventure game!"
          print "> "
          until (input = gets.chomp) == "exit"
            runner.__execute(input.downcase)
            print "> "
          end
          puts "Thanks for playing"
        end

      end




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
PROVIDE AN EXECUTION CONTEXT
    class Runner < BasicObject

      attr_accessor :__world, :__handled

      def initialize(world)
        @__world = world
      end

      def __handle!
        @__handled = true
      end
      
      def __execute(string)
        @__handled = false
        instance_eval(string)
        __puts "I don't understand" unless @__handled
      end

      def __puts(message)
        $stdout.puts(message)
      end

      def method_missing(name,*args)
        return *args.flatten.unshift(name.to_s)
      end

      def look(*args)
        __puts @__world.player.location.instance_eval(:@description)
        __handle!
      end

    end
Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
METAPROGRAMMING


  • method_missing

  • dynamically         writing code

  • evaluating       code in different contexts




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
COMMENTS? QUESTIONS?

  • Metaprogramming                Ruby - Pragmatic Bookshelf

  • kevin@kevingisi.com




  • Thank      you!




Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw

Mais conteúdo relacionado

Último

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Dynamic Ruby for Nubies

  • 1. DYNAMIC RUBY FOR NUBIES Nuby Hoedown MMX September 2nd, 2010 Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 2. Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 3. LANGUAGE Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 4. WHAT IS A DSL? • Domain-Specific Language Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 5. CUCUMBER IS A DSL Feature: Password recovery As a forgetful user I want to be able to recover my password So that I can get back into the site when I lose my password! Scenario: Recovering password Given I have signed up as a user     When I go to the home page      And I click "Recover your password"      And I fill in "Email" with "user@example.com"      And my email address is "user@example.com"      And I press "Reset my password"     Then I should receive an email     When I open the email      And I click the first link in the email      And I fill in "Password" with "simpsonsrock!"      And I fill in "Password Confirmation" with "simpsonsrock!"      And I press "Update password"     Then I should be on the dashboard page      And I should see "Your password has been reset" Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 6. REAL LANGUAGES • Rule-based • Pattern-matching • Very dull to read Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 7. DSL EVALUATION (RUBY) • Example: turn the monitor background color green Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 8. DSL EVALUATION (RUBY) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 9. DSL EVALUATION (RUBY) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 10. DSL EVALUATION (RUBY) • English: turn the monitor background color green • Ruby: turn(“monitor”, “background”, “#00FF00”) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 11. DSL EVALUATION (RUBY) • Example: turn the monitor background color green • Ruby: turn( the( monitor( background( color( green) ) ) ) ) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 12. DSL EVALUATION turn the monitor background color green class DSLObject      def method_missing(name,*args)     return name.to_s   end end # @dsl_object.green => "green" Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 13. DSL EVALUATION turn the monitor background color “green” class DSLObject   def color(name)     case name       when "green" : "#00FF00"       when "blue" : "#0000FF"       when "red" : "#FF0000"     end   end      def method_missing(name,*args)     return name.to_s   end end # @dsl_object.color green => NameError: undefined local variable or method `green' for #<Object:0x1001c8288> Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 14. PROBLEM! • How do we execute the code inside this object? • @dsl_object.color green • “green” is evaluated within the current scope, so unless it’s a variable, it doesn’t exist • (what we really mean is @dsl_object.color @dsl_object.green) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 15. LANGUAGE Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 16. BAD OBJECT-ORIENTATION Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 17. BETTER OBJECT-ORIENTATION Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 18. STATIC DISPATCH Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 19. DYNAMIC DISPATCH Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 20. CONTEXT-SWITCHING Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 21. RUBY HAS DYNAMIC DISPATCH • Ruby uses message-passing • @dsl_object.send(“col or green”) • Hey, some guy named Irb says “color green” Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 22. WRONG AGAIN! • Hmmm, do I have a method named “color green”? Nope • Do my ancestors have a method “color green”? Nope • Ooh! I’ll call method_missing(“color green”) • @dsl_object.send(“col or green”) #=> “color Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 23. CHANGING SCOPE @dsl_object.instance_eval do   # Everything in this block   # will treat @dsl_object   # as self   color green end # This is equivalent @dsl_object.instance_eval("color green") Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 24. DSL EVALUATION turn the monitor background “#00FF00” class DSLObject   def color(*args)     case args[0]       when "green" then "#00FF00"       when "blue" then "#0000FF"       when "red" then "#FF0000"     end   end      def method_missing(name,*args)     return *args.flatten.unshift(name.to_s)   end end # @dsl_object.instance_eval("background color green") => ["background","#00FF00"] Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 25. DSL EVALUATION turn the monitor [“background”, “#00FF00”] class DSLObject   def color(*args)     case args[0]       when "green" then "#00FF00"       when "blue" then "#0000FF"       when "red" then "#FF0000"     end   end      def method_missing(name,*args)     return *args.flatten.unshift(name.to_s)   end end # @dsl_object.instance_eval("monitor background color green") => ["monitor","background","#00FF00"] Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 26. DSL EVALUATION turn the [“monitor”,“background”, “#00FF00”] class DSLObject   def color(*args)     case args[0]       when "green" then "#00FF00"       when "blue" then "#0000FF"       when "red" then "#FF0000"     end   end   def the(*args)     return *args   end      def method_missing(name,*args)     return *args.flatten.unshift(name.to_s)   end end # @dsl_object.instance_eval("the monitor background color green") => ["monitor","background","#00FF00"] Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 27. DSL EVALUATION turn [“monitor”,“background”, “#00FF00”] Now we’re in normal programming territory Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 28. CONTRIVED EXAMPLES • Example: turn the beat around • With our DSL #=> turn [“beat”,“around”] • Valid syntax, bad semantics Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 29. SYNTAX LIMITATIONS • Example: Set course for the Hoth system • Can this be valid syntax? Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 30. SYNTAX LIMITATIONS • Example: Set course for the Hoth system • Set, Hoth => Constant undefined • for => reserved word • system => already defined (inherited from Object) Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 31. BLANK SLATE class DSLObject < BasicObject   def method_missing(name,*args)     return *args.flatten.unshift(name.to_s)   end   def const_missing(name)     eval(name.to_s_downcase)   end end # @dsl_object.instance_eval("Set course fer the Hoth system") # => ["Set","course","fer","the","Hoth","system"] Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 32. TEXT ADVENTURE GAMES Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 33. DOCUMENTATION Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 34. LANGUAGE Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 35. ENVIRONMENTS ARE HARD game = TextAdventureGame.new("My First Text Adventure") hallway = Location.new("A dark and quiet hallway") kitchen = Location.new("An abandoned kitchen") hall = Location.new("A banquet hall...strangely deserted") game.rooms << hallway game.rooms << kitchen game.rooms << hall hallway.north = kitchen kitchen.south = hallway kitchen.north = hall hall.south = kitchen Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 36. TEXT ADVENTURE WITH BLOCKS World.new("My First Text Adventure") do      location "hallway" do     description "A dark and quiet hallway"     north "kitchen"   end   location "kitchen" do     description "An abandoned kitchen"     south "hallway"   end   start "hallway" end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 37. PYTHONY TEXT ADVENTURE world "My First Text Adventure"      location "hallway"     description "A dark and quiet hallway"     north "kitchen"   location "kitchen"     description "An abandoned kitchen"     south "hallway"   start "hallway" Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 38. INTERPRETATION Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 39. BLOCKS • do..end • Delayed execution • Changes the execution scope • Is a real argument Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 40. CONTEXTS • instance_eval • class_eval • eval Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 41. WORLD require 'game' class World   attr_accessor :name, :locations, :player   def initialize(name,&block)     @name = name     @locations = {}     @player = Player.new     instance_eval &block   end   def location(name,&block)     @locations[name] = Location.new(name,&block)   end   def start(location)     @player.location = @locations[location]   end end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 42. LOCATION class Location   attr_accessor :name, :description, :exits   def initialize(name,&block)     @name = name     @exits = {}     instance_eval &block   end   def description(prose)     @description = prose   end   ["north","south","east","west"].each do |direction|     class_eval <<-END def #{direction}(location) @exits["#{direction}"] = location end END   end end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 43. PLAYER class Player   attr_accessor :location end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 44. HANDLING USER INPUT • Preprocess the input • Provide a context to execute • Manipulate the environment Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 45. PREPROCESS THE INPUT require 'world' require 'location' require 'player' require 'runner' class Game   def self.run(world)     runner = Runner.new(world)     puts "Welcome to the text adventure game!"     print "> "     until (input = gets.chomp) == "exit"       runner.__execute(input.downcase)       print "> "     end     puts "Thanks for playing"   end end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 46. PROVIDE AN EXECUTION CONTEXT class Runner < BasicObject   attr_accessor :__world, :__handled   def initialize(world)     @__world = world   end   def __handle!     @__handled = true   end      def __execute(string)     @__handled = false     instance_eval(string)     __puts "I don't understand" unless @__handled   end   def __puts(message)     $stdout.puts(message)   end   def method_missing(name,*args)     return *args.flatten.unshift(name.to_s)   end   def look(*args)     __puts @__world.player.location.instance_eval(:@description)     __handle!   end end Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 47. METAPROGRAMMING • method_missing • dynamically writing code • evaluating code in different contexts Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw
  • 48. COMMENTS? QUESTIONS? • Metaprogramming Ruby - Pragmatic Bookshelf • kevin@kevingisi.com • Thank you! Kevin W. Gisi | http://www.kevingisi.com | kevin@kevingisi.com | @gisikw

Notas do Editor