SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Rapid
Development with
Ruby/JRuby and
Rails
Lee Chuk Munn
Staff Engineer
Sun Microsystems

                   1
Why Ruby?




            2
What is Ruby?
• Created by Yukihiro “Matz” Matsumoto
  > Started around 1993, about the same time as Java
• What is a scripting language?
  > No compilation unit
         puts “Hello world”
  > Not compiled
  > Specialized syntax and data types
         subject.gsub(/before/, quot;afterquot;)
  > Maybe dynamic typing /duck typing
• Design to put the “fun” back into programming

                                                       3
Ruby Conventions
• ClassNames
• methods_names, variable_names
• visible?
• methods_with_side_effects!
• @instance_variable
• @@class_variable
• $global_variable
• A_CONSTANT, AnotherConstant
• MyClass.class_method – doc only
• MyClass#instance_method – doc only
                                       4
A Typical Ruby Class
     class Song                                     Properties
                  @@plays = 0
                  attr_accessor :name, :artist, :duration
                  def initialize(d, a, d)
                      @name = n; @artist = a; @duration = d
                  end
Constructor       public
                  def duration_in_minutes
                      @duration / 60
No return         end                               Virtual properties
                  def duration_in_minutes=(v)
                      @duration = (v * 60)
                  end                               Interpolated values
                  def play
                      @@plays += 1
                      puts quot;#{@name} plays #{@@plays}quot;
                      @@plays
                  end
                                                                          5
            end
Sample Execution

s = Song.new(“Cavatina”, “John Williams”, 200)

puts(“duration: #{s.duration}”)

puts “in mins: #{s.duration_in_minutes}”

s.duration_in_minutes = 4

puts “in mins: #{s.duration}”

s.play
                                                 6
Symbols
• :a_name is symbol, think identities
  > Refer to the name a_name, not the value that a_name
    may potentially hold
• Typically used in maps, property declaration,
  method names, any place you need a name/symbol
  :foo                                      foo
                     Symbol table
                           foo
                                       Memory location
                                          bar
                                                          7
Example Use of Symbols
attr_accessor :color, :age, :name                       Attribute

protected :deposit, :withdrawl                       Access modifiers

color = {
    :red => 0xf00,                   Maps
    :green => 0x0f0,
    :blue => 0x00f                          As keyword parameters
}

add_column :plugins, :price, :decimal,
      :precision => 8, :scale => 2, :default => 0

                                                                    8
Everything Returns a Value
• Returned not required
     def duration_in_minutes
        @duration / 60
     end
• Statements can be used as expressions
     gt = if (x > y) true else false

• Even defining a method has a return value
  > Returns nil



                                              9
Everything Is An Object
• 'Primitives' are objects
  > -1.abs
• nil is an object
  > nil.methods

• Classes are objects
  > Song.new – invoking the new method on 'Song' object
  > Create instances of themselves
• Code blocks are objects
  > They can be pass around, even as parameters
  > Blocks can be closure
                                                          10
Customization with Closure
class ColorButton
     attr_accessor :label, :r, :g, :b
     def initialize(l)
         label = 1
         r = 0x0f
         g = 0x0f
         b = 0x0f
         if block_given?
              yield self
         end
     end          b = ColorButton(“Press me”) do |button|
               button.r = 0xff
               # more stuff
               ...
            end                                             11
Common Uses of Closures
• Iteration
 [1,2,3].each {|i| puts i }
• Resource management
 File.new(quot;/etc/hostsquot;, quot;rquot;).each {|e| puts e }

• Callbacks
 widget.on_button_press { puts quot;Button Pressquot; }

• Initialization
 a = Array.new(5) {|i| i * i }


                         From http://onestepback.org/articles/10things/item3.html   12
Almost Everything is a Method Call
• In lots of cases, invoking method without knowing it
  array[i] = 0 – invoking the [] method
  1 + 2 + 3 – 1.+(2.+(3))
  str.length

• Methods can be invoked with or without parenthesis
  > Most developers chose the latter
  > Code looks more natural especially if you are doing DSL
• Methods can be overridden
  > Get operator overloading for free

                                                              13
Every Method Call is a Message
• obj.method(param) means having a method on the
  object in Java
• In Ruby, this means sending a message to the
  object
       obj.send(:method, param)
  is to send a '+' message with one value
       1+2+3
       1.send(:+, 2.send(:+, 3))
• Use respond_to? to find out if an object knows how
  to handle a message
       1.respond_to? :succ => true
                                                       14
So What Is the Big Deal?
public VCR
   def initialize                           varag
       @messages = []
   end
   def method_missing(method, *args, &block)
       @messages << [method, args, block]
   end                                 Push triplet onto array
   def play_back_to(obj)
       @messages.each do |method, args, block|
            obj.send(method, *args, &block)
       end
   end
end
                       From http://onestepback.org/articles/10things/page017.html   15
Example of Macro at the Language Level

vcr = VCR.new
vcr.sub!(/Java/) { |match| match.reverse }
vcr.upcase!                                Capture a group of
vcr[11,5] = quot;Universequot;                     operations. Reapply
vcr << quot;!quot;                                 these on a separate
                                          object
string = quot;Hello Java Worldquot;
puts string

vcr.play_back_to(string)
puts string # => quot;Hello AVAJ Universequot;
                                                                 16
Duck Typing Instead of Interfaces
• Familiar with the idea of using interface to enforce
  contracts
  > An object can only be considered a thread if it
    implements Runnable
• If an object can behave like a thread, then should
  be considered as a thread
  > Runnable is irrelevant if it has run()
  > If it walks like a duck, talks like a duck, then we can treat
    it as a duck
    d = DuckLikeObject.new
    puts d.quack if d.responds_to :quack
                                                                    17
Reuse – Inheritance
• Supports inheritance

   class KaraokeSong < Song
       ...
       def to_s
           super + “[#{@lyrics}]”
       end




                                    18
Reuse - Mixins
• Multiple inheritance like mechanism call mixins
  defined by modules
  > A namespace
  > Can have methods
  > But cannot be instantiated
• Becomes part of a class when included a module is
  included in a class
  > The reverse is also possible by extending the module
    with an object


                                                           19
Mixin Example
module Stringify                         class MyNumber
    def stringify                             include Stringify
        if @value == 1                        def initialize(value)
             quot;Onequot;                                @value = value
        elsif @value == 2                     end
             quot;Twoquot;                            ...
        elsif @value == 3
             quot;Threequot;
        end
    end
end



     Stringify example http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/   20
Reuse – Modifying Existing Class
• Methods can be added to a class at any time
  > Applies to built in classes
• Can be frozen
class String
    def rot13
        self.tr(quot;A-Ma-mN-Zn-zquot;,quot;N-Zn-zA-Ma-mquot;)
    end
end

“hello world”.rot13 #=> uryyb jbeyq
                                                 21
Extremely Flexible and Dynamic
• One of the hallmarks of scripting languages
• Metaprogramming – programs that write or
  manipulate themselves
• Some of the stuff you can do
  > Trap missing methods and add them if you so desire
  > Kernel definition hooks eg. Adding a method
  > Create code and execute them on the fly




                                                         22
Example of Ruby's Malleability
class Foo
     def method_missing(name, *args)
         if args[0].is_a?(Proc)
              self.class.instance_eval do
                   define_method(name.to_s.chomp(quot;=quot;), args[0])
              end
         else
              super
         end
     end            f = Foo.new
end                 f.greet = lambda {|t| quot;Hello #{t}!quot;}
                f.greet quot;Hello SunTech Daysquot;


       Adapted from http://tech.rufy.com/2006/08/dynamically-add-methods-to-classes.html
                                                                                      23
DSLs with Ruby
• DSL is a language designed for a specific domain
  > Captures jargon in language
• Ruby's DSL is internal (Fowler)
  > Morph language into DSL
  > Java is external and/or API based
• Killer features for DSL with Ruby
  >   Paranthesis-less method invocation
  >   Closures
  >   Malleable and dynamc engine
  >   Variable argument list
  >   Symbols
                                                     24
DSL Example
PBJ Sandwich                           recipe quot;PBJ Sandwichquot;

ingredients:                           ingredients :bread 2.slice
- two slices of bread                  ingredients :peanut_butter 1.spoon
- one tablespoon of peanut butter      ingredients :jam 1.teaspoon
- one teaspoon of jam                  instructions do
                                           step 1 “spread peanut butter”
instructions:                              step 2 “spread jam...”
- spread peanut butter on bread            step 3 “place other slice...”
- spread jam on top of peanut butter   end
- place other slice of bread on top
                                       servings 1
                                       prep_time 2.minutes
servings: 1
prep time: 2 minutes

Adapted from http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages
                                                                                   25
This is great, but...
• Ruby language is different from Java
• Ruby platform is different from Java
• How can Java developers benefit?




                                         26
JRuby
•   Implementation of Ruby written in Java
•   Compatible with Ruby 1.8.6
•   Enables use of Java code in Ruby
•   Easier deployment
•   More libraries
•   More platforms
•   Less “political” resistence


                                             27
FreeTTS Example
• In Java
  VoiceManager vm = VoiceManager.getInstance();
  Voice voice = vm.getVoice(quot;kevin16quot;);
  voice.allocate();
  voice.speak(jTextArea1.getText());
  voice.deallocate();

• In Ruby
  require 'java'
  vm = com.sun.speech.freetts.VoiceManager.getInstance()
  voice = vm.getVoice(quot;kevin16quot;)
  voice.allocate()
  voice.speak(quot;Calling Java code from Rubyquot;)
  voice.deallocate()

• JRuby engine available through JSR-223 in JavaSE 6       28
Rapid
Development with
Ruby/JRuby and
Rails
Lee Chuk Munn
Staff Engineer
Sun Microsystems

                   29
3. Inserting New or Existing Slides
●   To add a new slide to your presentation, select
    Insert>Slide. You can also duplicate slides in the
    Slide Sorter using copy and paste.
●   To add a slide(s) from another presentation,
    copy and paste from one file to the other in
    the Slide Sorter.
●   To insert an entire presentation, select Insert>File.




                                                            30
Template – Text Slide
with Two Line Title and Subtitle
This is a Subtitle with Initial Caps Each Major Word

• To insert a Subtitle on other slides, copy and paste
  the Subtitle text block
• On a slide with a two line Title and Subtitle (as
  shown here) move the bullet text block down to
  make room for the Subtitle. You can also duplicate
  this slide and replace the content.



                                                         31
GlassFish V2


               32
33
34
35
36
37
38
39
40
41
42
43
44
Title Here
Lee Chuk Munn
Staff Engineer
Sun Microsystems

                   45

Más contenido relacionado

La actualidad más candente

Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubySATOSHI TAGOMORI
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovypaulbowler
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbowschrisbuckett
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 

La actualidad más candente (20)

Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012Groovy Domain Specific Languages - SpringOne2GX 2012
Groovy Domain Specific Languages - SpringOne2GX 2012
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
Groovy!
Groovy!Groovy!
Groovy!
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Groovy 2 and beyond
Groovy 2 and beyondGroovy 2 and beyond
Groovy 2 and beyond
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in Ruby
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbows
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 

Destacado

Building A Mini Google High Performance Computing In Ruby Presentation 1
Building A Mini Google  High Performance Computing In Ruby Presentation 1Building A Mini Google  High Performance Computing In Ruby Presentation 1
Building A Mini Google High Performance Computing In Ruby Presentation 1elliando dias
 
8.4 defn of logarithms
8.4 defn of logarithms8.4 defn of logarithms
8.4 defn of logarithmsandreagoings
 
Infrastructure Engineering
Infrastructure EngineeringInfrastructure Engineering
Infrastructure Engineeringelliando dias
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmerselliando dias
 

Destacado (6)

Warrior scribe may '13 pdf
Warrior scribe may '13 pdfWarrior scribe may '13 pdf
Warrior scribe may '13 pdf
 
Building A Mini Google High Performance Computing In Ruby Presentation 1
Building A Mini Google  High Performance Computing In Ruby Presentation 1Building A Mini Google  High Performance Computing In Ruby Presentation 1
Building A Mini Google High Performance Computing In Ruby Presentation 1
 
8.4 defn of logarithms
8.4 defn of logarithms8.4 defn of logarithms
8.4 defn of logarithms
 
Infrastructure Engineering
Infrastructure EngineeringInfrastructure Engineering
Infrastructure Engineering
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 

Similar a Rapid Development with Ruby/JRuby and Rails

Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Aslak Hellesøy
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Benjamin Bock
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de RailsFabio Akita
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivoFabio Kung
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 

Similar a Rapid Development with Ruby/JRuby and Rails (20)

Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
 
Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 

Más de elliando dias

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slideselliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScriptelliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de containerelliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Librarieselliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Webelliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduinoelliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorceryelliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Designelliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makeselliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebookelliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Studyelliando dias
 

Más de elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Último

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
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 Processorsdebabhi2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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?Igalia
 
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...Martijn de Jong
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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?
 
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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Rapid Development with Ruby/JRuby and Rails

  • 1. Rapid Development with Ruby/JRuby and Rails Lee Chuk Munn Staff Engineer Sun Microsystems 1
  • 3. What is Ruby? • Created by Yukihiro “Matz” Matsumoto > Started around 1993, about the same time as Java • What is a scripting language? > No compilation unit puts “Hello world” > Not compiled > Specialized syntax and data types subject.gsub(/before/, quot;afterquot;) > Maybe dynamic typing /duck typing • Design to put the “fun” back into programming 3
  • 4. Ruby Conventions • ClassNames • methods_names, variable_names • visible? • methods_with_side_effects! • @instance_variable • @@class_variable • $global_variable • A_CONSTANT, AnotherConstant • MyClass.class_method – doc only • MyClass#instance_method – doc only 4
  • 5. A Typical Ruby Class class Song Properties @@plays = 0 attr_accessor :name, :artist, :duration def initialize(d, a, d) @name = n; @artist = a; @duration = d end Constructor public def duration_in_minutes @duration / 60 No return end Virtual properties def duration_in_minutes=(v) @duration = (v * 60) end Interpolated values def play @@plays += 1 puts quot;#{@name} plays #{@@plays}quot; @@plays end 5 end
  • 6. Sample Execution s = Song.new(“Cavatina”, “John Williams”, 200) puts(“duration: #{s.duration}”) puts “in mins: #{s.duration_in_minutes}” s.duration_in_minutes = 4 puts “in mins: #{s.duration}” s.play 6
  • 7. Symbols • :a_name is symbol, think identities > Refer to the name a_name, not the value that a_name may potentially hold • Typically used in maps, property declaration, method names, any place you need a name/symbol :foo foo Symbol table foo Memory location bar 7
  • 8. Example Use of Symbols attr_accessor :color, :age, :name Attribute protected :deposit, :withdrawl Access modifiers color = { :red => 0xf00, Maps :green => 0x0f0, :blue => 0x00f As keyword parameters } add_column :plugins, :price, :decimal, :precision => 8, :scale => 2, :default => 0 8
  • 9. Everything Returns a Value • Returned not required def duration_in_minutes @duration / 60 end • Statements can be used as expressions gt = if (x > y) true else false • Even defining a method has a return value > Returns nil 9
  • 10. Everything Is An Object • 'Primitives' are objects > -1.abs • nil is an object > nil.methods • Classes are objects > Song.new – invoking the new method on 'Song' object > Create instances of themselves • Code blocks are objects > They can be pass around, even as parameters > Blocks can be closure 10
  • 11. Customization with Closure class ColorButton attr_accessor :label, :r, :g, :b def initialize(l) label = 1 r = 0x0f g = 0x0f b = 0x0f if block_given? yield self end end b = ColorButton(“Press me”) do |button| button.r = 0xff # more stuff ... end 11
  • 12. Common Uses of Closures • Iteration [1,2,3].each {|i| puts i } • Resource management File.new(quot;/etc/hostsquot;, quot;rquot;).each {|e| puts e } • Callbacks widget.on_button_press { puts quot;Button Pressquot; } • Initialization a = Array.new(5) {|i| i * i } From http://onestepback.org/articles/10things/item3.html 12
  • 13. Almost Everything is a Method Call • In lots of cases, invoking method without knowing it array[i] = 0 – invoking the [] method 1 + 2 + 3 – 1.+(2.+(3)) str.length • Methods can be invoked with or without parenthesis > Most developers chose the latter > Code looks more natural especially if you are doing DSL • Methods can be overridden > Get operator overloading for free 13
  • 14. Every Method Call is a Message • obj.method(param) means having a method on the object in Java • In Ruby, this means sending a message to the object obj.send(:method, param) is to send a '+' message with one value 1+2+3 1.send(:+, 2.send(:+, 3)) • Use respond_to? to find out if an object knows how to handle a message 1.respond_to? :succ => true 14
  • 15. So What Is the Big Deal? public VCR def initialize varag @messages = [] end def method_missing(method, *args, &block) @messages << [method, args, block] end Push triplet onto array def play_back_to(obj) @messages.each do |method, args, block| obj.send(method, *args, &block) end end end From http://onestepback.org/articles/10things/page017.html 15
  • 16. Example of Macro at the Language Level vcr = VCR.new vcr.sub!(/Java/) { |match| match.reverse } vcr.upcase! Capture a group of vcr[11,5] = quot;Universequot; operations. Reapply vcr << quot;!quot; these on a separate object string = quot;Hello Java Worldquot; puts string vcr.play_back_to(string) puts string # => quot;Hello AVAJ Universequot; 16
  • 17. Duck Typing Instead of Interfaces • Familiar with the idea of using interface to enforce contracts > An object can only be considered a thread if it implements Runnable • If an object can behave like a thread, then should be considered as a thread > Runnable is irrelevant if it has run() > If it walks like a duck, talks like a duck, then we can treat it as a duck d = DuckLikeObject.new puts d.quack if d.responds_to :quack 17
  • 18. Reuse – Inheritance • Supports inheritance class KaraokeSong < Song ... def to_s super + “[#{@lyrics}]” end 18
  • 19. Reuse - Mixins • Multiple inheritance like mechanism call mixins defined by modules > A namespace > Can have methods > But cannot be instantiated • Becomes part of a class when included a module is included in a class > The reverse is also possible by extending the module with an object 19
  • 20. Mixin Example module Stringify class MyNumber def stringify include Stringify if @value == 1 def initialize(value) quot;Onequot; @value = value elsif @value == 2 end quot;Twoquot; ... elsif @value == 3 quot;Threequot; end end end Stringify example http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/ 20
  • 21. Reuse – Modifying Existing Class • Methods can be added to a class at any time > Applies to built in classes • Can be frozen class String def rot13 self.tr(quot;A-Ma-mN-Zn-zquot;,quot;N-Zn-zA-Ma-mquot;) end end “hello world”.rot13 #=> uryyb jbeyq 21
  • 22. Extremely Flexible and Dynamic • One of the hallmarks of scripting languages • Metaprogramming – programs that write or manipulate themselves • Some of the stuff you can do > Trap missing methods and add them if you so desire > Kernel definition hooks eg. Adding a method > Create code and execute them on the fly 22
  • 23. Example of Ruby's Malleability class Foo def method_missing(name, *args) if args[0].is_a?(Proc) self.class.instance_eval do define_method(name.to_s.chomp(quot;=quot;), args[0]) end else super end end f = Foo.new end f.greet = lambda {|t| quot;Hello #{t}!quot;} f.greet quot;Hello SunTech Daysquot; Adapted from http://tech.rufy.com/2006/08/dynamically-add-methods-to-classes.html 23
  • 24. DSLs with Ruby • DSL is a language designed for a specific domain > Captures jargon in language • Ruby's DSL is internal (Fowler) > Morph language into DSL > Java is external and/or API based • Killer features for DSL with Ruby > Paranthesis-less method invocation > Closures > Malleable and dynamc engine > Variable argument list > Symbols 24
  • 25. DSL Example PBJ Sandwich recipe quot;PBJ Sandwichquot; ingredients: ingredients :bread 2.slice - two slices of bread ingredients :peanut_butter 1.spoon - one tablespoon of peanut butter ingredients :jam 1.teaspoon - one teaspoon of jam instructions do step 1 “spread peanut butter” instructions: step 2 “spread jam...” - spread peanut butter on bread step 3 “place other slice...” - spread jam on top of peanut butter end - place other slice of bread on top servings 1 prep_time 2.minutes servings: 1 prep time: 2 minutes Adapted from http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages 25
  • 26. This is great, but... • Ruby language is different from Java • Ruby platform is different from Java • How can Java developers benefit? 26
  • 27. JRuby • Implementation of Ruby written in Java • Compatible with Ruby 1.8.6 • Enables use of Java code in Ruby • Easier deployment • More libraries • More platforms • Less “political” resistence 27
  • 28. FreeTTS Example • In Java VoiceManager vm = VoiceManager.getInstance(); Voice voice = vm.getVoice(quot;kevin16quot;); voice.allocate(); voice.speak(jTextArea1.getText()); voice.deallocate(); • In Ruby require 'java' vm = com.sun.speech.freetts.VoiceManager.getInstance() voice = vm.getVoice(quot;kevin16quot;) voice.allocate() voice.speak(quot;Calling Java code from Rubyquot;) voice.deallocate() • JRuby engine available through JSR-223 in JavaSE 6 28
  • 29. Rapid Development with Ruby/JRuby and Rails Lee Chuk Munn Staff Engineer Sun Microsystems 29
  • 30. 3. Inserting New or Existing Slides ● To add a new slide to your presentation, select Insert>Slide. You can also duplicate slides in the Slide Sorter using copy and paste. ● To add a slide(s) from another presentation, copy and paste from one file to the other in the Slide Sorter. ● To insert an entire presentation, select Insert>File. 30
  • 31. Template – Text Slide with Two Line Title and Subtitle This is a Subtitle with Initial Caps Each Major Word • To insert a Subtitle on other slides, copy and paste the Subtitle text block • On a slide with a two line Title and Subtitle (as shown here) move the bullet text block down to make room for the Subtitle. You can also duplicate this slide and replace the content. 31
  • 33. 33
  • 34. 34
  • 35. 35
  • 36. 36
  • 37. 37
  • 38. 38
  • 39. 39
  • 40. 40
  • 41. 41
  • 42. 42
  • 43. 43
  • 44. 44
  • 45. Title Here Lee Chuk Munn Staff Engineer Sun Microsystems 45