SlideShare a Scribd company logo
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

More Related Content

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 

Featured

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
Marius 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 ChatGPT
Expeed 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 Engineerings
Pixeldarts
 
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
ThinkNow
 
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
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
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
Neil 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 2024
Albert 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 Insights
Kurio // 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 2024
Search 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 summary
SpeakerHub
 
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 Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit 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 management
MindGenius
 
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
 

Featured (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

Editor's Notes