SlideShare une entreprise Scribd logo
1  sur  50
Télécharger pour lire hors ligne
Introduction to
     JRuby
       Frederic Jean
    fred@fredjean.net




                        1
First Encounter



                  2
Hello JRuby



              3
Configuration
                 DSLs
                                     Glue, Wiring




                         Dynamic Layer
                        Application Code




                        Stable Layer
                    Java, Statically typed
                      Legacy libraries




http://olabini.com/blog/2008/01/language-explorations/


                                                         4
Develop, Deploy, Build, Test, Monitor
                                                  Configuration
                              DSLs
                                                  Glue, Wiring
External System Integration




                                      Dynamic Layer
                                     Application Code




                                     Stable Layer
                                 Java, Statically typed
                                   Legacy libraries




                                                                                                         5
Ruby



       6
Ruby is...

• Dynamically Typed
• Strongly Typed
• Everything is An Object


                            7
Dynamic Typing

• Variables Are Not Typed
• Type Evaluated at Run Time
• Duck Typing


                               8
(Almost) Everything is
     an Object


                         9
Ruby Literals
# Strings
quot;This is a Stringquot;
'This is also a String'
%{So is this}

# Numbers
1, 0xa2, 0644, 3.14, 2.2e10

# Arrays and Hashes
['John', 'Henry', 'Mark']
{ :hello => quot;bonjourquot;, :bye => quot;au revoirquot;}

# Regular Expressions
quot;Mary had a little lambquot; =~ /little/
quot;The London Bridgequot; =~ %r{london}i

# Ranges
(1..100) # inclusive
(1...100) # exclusive




                                              10
Symbols

              :symbol


• String-like construct
• Only one copy in memory

                            11
Ruby Type
quot;helloquot;.class   #   =>   String
1.class         #   =>   Fixnum
10.3.class      #   =>   Float
[].class        #   =>   Array
{}.class        #   =>   Hash
Kernel.class    #   =>   Module
Object.class    #   =>   Class
:symbol.class   #   =>   Symbol




                                  12
kind_of? vs respond_to?
   puts 10.instance_of? Fixnum

   puts 10.respond_to? :odd?
   puts 10.respond_to? :between?




  http://localhost:4567/code/instance_of.rb
                                              13
Blocks
['John', 'Henry', 'Mark'].each { |name| puts quot;#{name}quot;}

File.open(quot;/tmp/password.txtquot;) do |input|
  text = input.read
end




                                                          14
Ruby Classes
class Person
  attr_accessor :name, :title
end

p = Person.new




                                15
Open Classes
     class Fixnum
       def odd?
         self % 2 == 1
       end

       def even?
         self % 2 == 0
       end
     end


http://localhost:4567/code/fixnum.rb
                                      16
Namespacing
module Net
  module FredJean
    class MyClass
    end
  end
end

Net::FredJean::MyClass




                         17
Mixins
     module Parity
       def even?
         self % 2 == 0
       end

       def odd?
         self % 2 == 1
       end
     end


http://localhost:4567/code/parity.rb
                                       18
Mixins
class Person
  include Enumerable

  attr_accessor :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end

  def <=>(other)
    self.last_name <=> other.last_name && self.first_name <=> other.last_name
  end

  def to_s
    quot;#{first_name} #{last_name}quot;
  end
end




              http://localhost:4567/code/sorting.rb
                                                                                19
Mixin Reflection

puts String.include? Enumerable
puts String.instance_of? Enumerable
puts String.kind_of? Enumerable




    http://localhost:4567/code/include.rb
                                            20
Executable Class Definition
   class Message
     if RUBY_PLATFORM =~ /java/i
       def hello
         puts quot;Hello From JRubyquot;
       end
     end
   end



     http://localhost:4567/code/env.rb
                                         21
JRuby



        22
JRuby

• Ruby Implementation on the JVM
• Compatible with Ruby 1.8.6
• Native Multithreading
• Full Access to Java Libraries

                                   23
JRuby Hello World

java.lang.System.out.println quot;Hello JRuby!quot;




      http://localhost:4567/code/jruby_hello.rb
                                                  24
Java Integration

 require 'java'




                   25
JI: Ruby-like Methods
           Java                        Ruby
Locale.US                    Locale::US
System.currentTimeMillis()   System.current_time_millis
locale.getLanguage()         locale.language
date.getTime()               date.time
date.setTime(10)             date.time = 10
file.isDirectory()           file.directory?




                                                          26
JI: Java Extensions
     h = java.util.HashMap.new
     h[quot;keyquot;] = quot;valuequot;
     h[quot;keyquot;]
     # => quot;valuequot;
     h.get(quot;keyquot;)
     # => quot;valuequot;
     h.each {|k,v| puts k + ' => ' + v}
     # key => value
     h.to_a
     # => [[quot;keyquot;, quot;valuequot;]]




http://localhost:4567/code/ji/extensions.rb
                                              27
JI: Java Extensions
module java::util::Map
  include Enumerable

  def each(&block)
    entrySet.each { |pair| block.call([pair.key, pair.value]) }
  end

  def [](key)
    get(key)
  end

  def []=(key,val)
    put(key,val)
    val
  end
end




                                                                  28
JI: Open Java Classes
class Java::JavaLang::Integer
  def even?
    int_value % 2 == 0
  end

  def odd?
    int_value % 2 == 1
  end
end


  http://localhost:4567/code/ji/integer.rb
                                             29
JI: Interface Conversion
 package java.util.concurrent;

 public class Executors {
    // ...
    public static Callable callable(Runnable r) {
       // ...
    }
 }




                                                    30
JI: Interface Conversion
class SimpleRubyObject
  def run
    puts quot;hiquot;
  end
end

callable = Executors.callable(SimpleRubyObject.new)
callable.call




 http://localhost:4567/code/ji/if_conversion.rb
                                                      31
JI: Closure Conversion

callable = Executors.callable { puts quot;hiquot; }
callable.call




   http://localhost:4567/code/ji/closure_conversion.rb
                                                         32
Develop, Deploy, Build, Test, Monitor
                                                  Configuration
                              DSLs
                                                  Glue, Wiring
External System Integration




                                      Dynamic Layer
                                     Application Code




                                     Stable Layer
                                 Java, Statically typed
                                   Legacy libraries




                                                                                                         33
Usage

• Runtime
• Wrapper around Java Code
• Calling From Java
• Utilities

                             34
JRuby as a Runtime



                     35
JRuby on Rails

• Ruby on Rails 2.1 and above is supported
• Direct support in Glassfish v3 Prelude
• http://kenai.com
• http://mediacast.sun.com

                                             36
Warbler

jruby -S gem install warbler
jruby -S warble config
# => config/warble.rb
jruby -S warble
# => myapp.war




                               37
webmate
require 'rubygems'
require 'sinatra'

get '/*' do
  file, line = request.path_info.split(/:/)
  local_file = File.join(Dir.pwd, file)
  if (File.exists?(local_file))
    redirect quot;txmt://open/?url=file://#{local_file}&line=#{line}quot;
  else
    not_found
  end
end




      http://localhost:4567/code/webmate.rb
                                                                    38
Wrapping Java Code



                     39
Swing Applications

frame = JFrame.new(quot;Hello Swingquot;)


   • Reduce verbosity
   • Simplify event handlers
        http://localhost:4567/code/swing.rb
                                              40
RSpec Testing Java
 describe quot;An emptyquot;, HashMap do
   before :each do
     @hash_map = HashMap.new
   end

   it quot;should be able to add an entry to itquot; do
     @hash_map.put quot;fooquot;, quot;barquot;
     @hash_map.get(quot;fooquot;).should == quot;barquot;
   end
 end


 JTestr Provides Ant and Maven integration
          http://jtestr.codehaus.org

http://localhost:4567/code/hashmap_spec.rb
                                                  41
Java Calling JRuby



                     42
JSR-223

• Ships with Java 6
• Supports JRuby 1.1
        https://scripting.dev.java.net/



                                          43
JRuby Runtime

• Support the current release
• Specific to JRuby
• Subject to change


                                44
Spring Scripting

<lang:jruby id=quot;limequot; script-interfaces=quot;springruby.Limequot;
        script-source=quot;classpath:lime.rbquot;/>




                                                            45
Utilities



            46
Develop, Deploy, Build, Test, Monitor
                                                  Configuration
                              DSLs
                                                  Glue, Wiring
External System Integration




                                      Dynamic Layer
                                     Application Code




                                     Stable Layer
                                 Java, Statically typed
                                   Legacy libraries




                                                                                                         47
Build Utilities

• Rake
• Raven
• Buildr


                             48
Conclusion



             49
Resources
• http://jruby.org
• http://wiki.jruby.org
• http://jruby.kenai.com
• http://jtester.codehaus.org
• http://raven.rubyforge.org
• http://buildr.apache.org
                                50

Contenu connexe

Tendances

Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot WorldSchalk Cronjé
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyMatthew Gaudet
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They ExistRafael Dohms
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMKris Mok
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)Ron Munitz
 
Caching and Synchronization in Flex
Caching and Synchronization in FlexCaching and Synchronization in Flex
Caching and Synchronization in Flexzpinter
 
Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)Stephen Chin
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubySATOSHI TAGOMORI
 
JVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesJVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesKris Mok
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free ProgrammingStephen Chin
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails introMiguel Pastor
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
 
Greach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovyGreach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovyIván López Martín
 

Tendances (19)

Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRuby
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They Exist
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VM
 
Debugging on rails
Debugging on railsDebugging on rails
Debugging on rails
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Caching and Synchronization in Flex
Caching and Synchronization in FlexCaching and Synchronization in Flex
Caching and Synchronization in Flex
 
Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in Ruby
 
JVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesJVM: A Platform for Multiple Languages
JVM: A Platform for Multiple Languages
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free Programming
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
 
You suck at Memory Analysis
You suck at Memory AnalysisYou suck at Memory Analysis
You suck at Memory Analysis
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUG
 
Dart
DartDart
Dart
 
Greach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovyGreach 2014 - Metaprogramming with groovy
Greach 2014 - Metaprogramming with groovy
 

En vedette

J Ruby Kungfu Rails
J Ruby   Kungfu RailsJ Ruby   Kungfu Rails
J Ruby Kungfu RailsDaniel Lv
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRubyAmit Solanki
 
Abstraction of JRuby Kaigi2010
Abstraction of  JRuby Kaigi2010Abstraction of  JRuby Kaigi2010
Abstraction of JRuby Kaigi2010Koichiro Ohba
 
Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Charles Nutter
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRubyajuckel
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worldsChristopher Spring
 
Focuslight, Jobs and OSS - HackGirls bar vol.2
Focuslight, Jobs and OSS - HackGirls bar vol.2Focuslight, Jobs and OSS - HackGirls bar vol.2
Focuslight, Jobs and OSS - HackGirls bar vol.2Koichiro Ohba
 
The Breakthroughs
The BreakthroughsThe Breakthroughs
The Breakthroughsclarissebai
 
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...Justin Pirie
 
College Parents Humor: From Acceptance through Move-In
College Parents Humor: From Acceptance through Move-InCollege Parents Humor: From Acceptance through Move-In
College Parents Humor: From Acceptance through Move-InCollege Parents of America
 

En vedette (15)

S
SS
S
 
J Ruby Kungfu Rails
J Ruby   Kungfu RailsJ Ruby   Kungfu Rails
J Ruby Kungfu Rails
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
Abstraction of JRuby Kaigi2010
Abstraction of  JRuby Kaigi2010Abstraction of  JRuby Kaigi2010
Abstraction of JRuby Kaigi2010
 
Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012
 
Megyünk a Balcsira?
Megyünk a Balcsira?Megyünk a Balcsira?
Megyünk a Balcsira?
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
Focuslight, Jobs and OSS - HackGirls bar vol.2
Focuslight, Jobs and OSS - HackGirls bar vol.2Focuslight, Jobs and OSS - HackGirls bar vol.2
Focuslight, Jobs and OSS - HackGirls bar vol.2
 
20320140503006
2032014050300620320140503006
20320140503006
 
Power Ruby
Power RubyPower Ruby
Power Ruby
 
The Breakthroughs
The BreakthroughsThe Breakthroughs
The Breakthroughs
 
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...
HostingCon 2011- How Not Just to Survive but Thrive in the Evolving Hosting M...
 
College Parents Humor: From Acceptance through Move-In
College Parents Humor: From Acceptance through Move-InCollege Parents Humor: From Acceptance through Move-In
College Parents Humor: From Acceptance through Move-In
 
45 lessons in life
45 lessons in life45 lessons in life
45 lessons in life
 

Similaire à Intro to J Ruby

Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSLjodosha
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0Jan Sifra
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manormartinbtt
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012alexismidon
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java programming guide - quick reference
Java programming guide -  quick referenceJava programming guide -  quick reference
Java programming guide - quick referenceTutorials Tips Tricks
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick ReferenceFrescatiStory
 

Similaire à Intro to J Ruby (20)

Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Jet presentation
Jet presentationJet presentation
Jet presentation
 
JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSL
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manor
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei Presentation
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
JRuby Basics
JRuby BasicsJRuby Basics
JRuby Basics
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java programming guide - quick reference
Java programming guide -  quick referenceJava programming guide -  quick reference
Java programming guide - quick reference
 
Java cheat sheet
Java cheat sheetJava cheat sheet
Java cheat sheet
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick Reference
 

Intro to J Ruby

  • 1. Introduction to JRuby Frederic Jean fred@fredjean.net 1
  • 4. Configuration DSLs Glue, Wiring Dynamic Layer Application Code Stable Layer Java, Statically typed Legacy libraries http://olabini.com/blog/2008/01/language-explorations/ 4
  • 5. Develop, Deploy, Build, Test, Monitor Configuration DSLs Glue, Wiring External System Integration Dynamic Layer Application Code Stable Layer Java, Statically typed Legacy libraries 5
  • 6. Ruby 6
  • 7. Ruby is... • Dynamically Typed • Strongly Typed • Everything is An Object 7
  • 8. Dynamic Typing • Variables Are Not Typed • Type Evaluated at Run Time • Duck Typing 8
  • 10. Ruby Literals # Strings quot;This is a Stringquot; 'This is also a String' %{So is this} # Numbers 1, 0xa2, 0644, 3.14, 2.2e10 # Arrays and Hashes ['John', 'Henry', 'Mark'] { :hello => quot;bonjourquot;, :bye => quot;au revoirquot;} # Regular Expressions quot;Mary had a little lambquot; =~ /little/ quot;The London Bridgequot; =~ %r{london}i # Ranges (1..100) # inclusive (1...100) # exclusive 10
  • 11. Symbols :symbol • String-like construct • Only one copy in memory 11
  • 12. Ruby Type quot;helloquot;.class # => String 1.class # => Fixnum 10.3.class # => Float [].class # => Array {}.class # => Hash Kernel.class # => Module Object.class # => Class :symbol.class # => Symbol 12
  • 13. kind_of? vs respond_to? puts 10.instance_of? Fixnum puts 10.respond_to? :odd? puts 10.respond_to? :between? http://localhost:4567/code/instance_of.rb 13
  • 14. Blocks ['John', 'Henry', 'Mark'].each { |name| puts quot;#{name}quot;} File.open(quot;/tmp/password.txtquot;) do |input| text = input.read end 14
  • 15. Ruby Classes class Person attr_accessor :name, :title end p = Person.new 15
  • 16. Open Classes class Fixnum def odd? self % 2 == 1 end def even? self % 2 == 0 end end http://localhost:4567/code/fixnum.rb 16
  • 17. Namespacing module Net module FredJean class MyClass end end end Net::FredJean::MyClass 17
  • 18. Mixins module Parity def even? self % 2 == 0 end def odd? self % 2 == 1 end end http://localhost:4567/code/parity.rb 18
  • 19. Mixins class Person include Enumerable attr_accessor :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def <=>(other) self.last_name <=> other.last_name && self.first_name <=> other.last_name end def to_s quot;#{first_name} #{last_name}quot; end end http://localhost:4567/code/sorting.rb 19
  • 20. Mixin Reflection puts String.include? Enumerable puts String.instance_of? Enumerable puts String.kind_of? Enumerable http://localhost:4567/code/include.rb 20
  • 21. Executable Class Definition class Message if RUBY_PLATFORM =~ /java/i def hello puts quot;Hello From JRubyquot; end end end http://localhost:4567/code/env.rb 21
  • 22. JRuby 22
  • 23. JRuby • Ruby Implementation on the JVM • Compatible with Ruby 1.8.6 • Native Multithreading • Full Access to Java Libraries 23
  • 24. JRuby Hello World java.lang.System.out.println quot;Hello JRuby!quot; http://localhost:4567/code/jruby_hello.rb 24
  • 26. JI: Ruby-like Methods Java Ruby Locale.US Locale::US System.currentTimeMillis() System.current_time_millis locale.getLanguage() locale.language date.getTime() date.time date.setTime(10) date.time = 10 file.isDirectory() file.directory? 26
  • 27. JI: Java Extensions h = java.util.HashMap.new h[quot;keyquot;] = quot;valuequot; h[quot;keyquot;] # => quot;valuequot; h.get(quot;keyquot;) # => quot;valuequot; h.each {|k,v| puts k + ' => ' + v} # key => value h.to_a # => [[quot;keyquot;, quot;valuequot;]] http://localhost:4567/code/ji/extensions.rb 27
  • 28. JI: Java Extensions module java::util::Map include Enumerable def each(&block) entrySet.each { |pair| block.call([pair.key, pair.value]) } end def [](key) get(key) end def []=(key,val) put(key,val) val end end 28
  • 29. JI: Open Java Classes class Java::JavaLang::Integer def even? int_value % 2 == 0 end def odd? int_value % 2 == 1 end end http://localhost:4567/code/ji/integer.rb 29
  • 30. JI: Interface Conversion package java.util.concurrent; public class Executors { // ... public static Callable callable(Runnable r) { // ... } } 30
  • 31. JI: Interface Conversion class SimpleRubyObject def run puts quot;hiquot; end end callable = Executors.callable(SimpleRubyObject.new) callable.call http://localhost:4567/code/ji/if_conversion.rb 31
  • 32. JI: Closure Conversion callable = Executors.callable { puts quot;hiquot; } callable.call http://localhost:4567/code/ji/closure_conversion.rb 32
  • 33. Develop, Deploy, Build, Test, Monitor Configuration DSLs Glue, Wiring External System Integration Dynamic Layer Application Code Stable Layer Java, Statically typed Legacy libraries 33
  • 34. Usage • Runtime • Wrapper around Java Code • Calling From Java • Utilities 34
  • 35. JRuby as a Runtime 35
  • 36. JRuby on Rails • Ruby on Rails 2.1 and above is supported • Direct support in Glassfish v3 Prelude • http://kenai.com • http://mediacast.sun.com 36
  • 37. Warbler jruby -S gem install warbler jruby -S warble config # => config/warble.rb jruby -S warble # => myapp.war 37
  • 38. webmate require 'rubygems' require 'sinatra' get '/*' do file, line = request.path_info.split(/:/) local_file = File.join(Dir.pwd, file) if (File.exists?(local_file)) redirect quot;txmt://open/?url=file://#{local_file}&line=#{line}quot; else not_found end end http://localhost:4567/code/webmate.rb 38
  • 40. Swing Applications frame = JFrame.new(quot;Hello Swingquot;) • Reduce verbosity • Simplify event handlers http://localhost:4567/code/swing.rb 40
  • 41. RSpec Testing Java describe quot;An emptyquot;, HashMap do before :each do @hash_map = HashMap.new end it quot;should be able to add an entry to itquot; do @hash_map.put quot;fooquot;, quot;barquot; @hash_map.get(quot;fooquot;).should == quot;barquot; end end JTestr Provides Ant and Maven integration http://jtestr.codehaus.org http://localhost:4567/code/hashmap_spec.rb 41
  • 43. JSR-223 • Ships with Java 6 • Supports JRuby 1.1 https://scripting.dev.java.net/ 43
  • 44. JRuby Runtime • Support the current release • Specific to JRuby • Subject to change 44
  • 45. Spring Scripting <lang:jruby id=quot;limequot; script-interfaces=quot;springruby.Limequot; script-source=quot;classpath:lime.rbquot;/> 45
  • 46. Utilities 46
  • 47. Develop, Deploy, Build, Test, Monitor Configuration DSLs Glue, Wiring External System Integration Dynamic Layer Application Code Stable Layer Java, Statically typed Legacy libraries 47
  • 48. Build Utilities • Rake • Raven • Buildr 48
  • 50. Resources • http://jruby.org • http://wiki.jruby.org • http://jruby.kenai.com • http://jtester.codehaus.org • http://raven.rubyforge.org • http://buildr.apache.org 50