This document provides an introduction to JRuby, which allows Ruby code to run on the Java Virtual Machine. It discusses key features of Ruby like dynamic typing and everything being an object. It then covers how to integrate Ruby and Java code through the Java integration layer, including calling Java from Ruby and converting interfaces. The document concludes by discussing using JRuby for applications, testing Java with RSpec, and build utilities.
11. Open Classes
class Fixnum
def odd?
self % 2 == 1
end
def even?
self % 2 == 0
end
end
http://localhost:4567/code/fixnum.rb
12. Mixins
module Parity
def even?
self % 2 == 0
end
def odd?
self % 2 == 1
end
end
http://localhost:4567/code/parity.rb
13. 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)
if self.last_name == other.last_name
self.first_name <=> other.first_name
else
self.last_name <=> other.last_name
end
end
def to_s
quot;#{first_name} #{last_name}quot;
end
end
http://localhost:4567/code/sorting.rb
20. 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
21. 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
22. JI: Interface Conversion
package java.util.concurrent;
public class Executors {
// ...
public static Callable callable(Runnable r) {
// ...
}
}
23. 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
28. JRuby on Rails
• Wrap Rails app into a war file
• Direct support in Glassfish v3 Prelude
• http://kenai.com
• http://mediacast.sun.com
29. 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
32. 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