1. From Java To Ruby … and Back
Anil Hemrajani, Founder, BigUniverse.com
TS-4868, anil@biguniverse.com
2. 2008 JavaOneSM
Conference | java.sun.com/javaone | 2
Agenda
My Background & BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java™ platform & Ruby Compared
Using the Java platform & Ruby Together
Tools
Wrap Up & Resources
3. 2008 JavaOneSM
Conference | java.sun.com/javaone | 3
My Background
20+ years of software development
• Custom apps & products - AT&T, IBM, AOL, Fannie Mae, startups. . .
• Programming Languages
• Since 2006 - Working exclusively with Ruby/Rails
• 1995 to 2006 - 11+ with the Java platform
• Before that - C , C++, Unix®
Shell software, PERL, etc.
• OS, Database, Tools, etc. - Unix, Linux, Windows, Mac OS X, MySQL™,
Oracle®
, Sybase, Informix, Eclipse, NetBeans™, Visual Café, JBuilder
software and many more!
Author & speaker
• Published top-rated book on Java™ platform (available in 4 languages)
• Published dozens articles
• Presented in 4 continents to thousands of attendees
Other: Won several industry awards, founder of two companies…
details on visualpatterns.com.
At present: BigUniverse.com
4. 2008 JavaOneSM
Conference | java.sun.com/javaone | 4
About BigUniverse.com
A World of Online Children’s Picture Books
Built using:
• Ubuntu Linux (using Xen Virtualization)
• Apache Mongrel Cluster (may move to Java Server soon)
• Ruby Rails
• MySQL
• OpenLaszlo
• DHTML/AJAX
• Development on combination of Mac OS X and Windows
Tools Used: Eclipse, Aqua Studio CocoaMySQL, Ruby irb Rails
script/console, capistrano deprec, and more
“Read, create, publish buy
children’s picture books”
5. 2008 JavaOneSM
Conference | java.sun.com/javaone | 5
Big Universe Website Products
Website
Books, tools, blogs, global awareness…
Big Universe Author™
Book creation publishing tool with 7,000
vector graphic cliparts
Big Universe Reader™
300+ (and growing) high-quality fiction non-
fiction books readable online
6. 2008 JavaOneSM
Conference | java.sun.com/javaone | 6
Why We Chose Ruby?
Primarily because of the Rails framework
I resisted the hype of Rails for 1+ year but finally:
• Took the advise of many intelligent pragmatic developers I know
• Spent 4+ weeks developing with it
• Conclusion? The hype is mostly true; productivity is very high
Business Technical benefits seen so far
Rapid prototyping/development because:
• Language is concise and easy to read
• Single-stack application framework (web MVC, ORM, unit testing…)
• Almost no configuration required (No XML hell!)
• Dynamically typed
• Can be used for full OO applications or just procedural scripting
• No compilation (prediction: in 5+ years, we will do away with compilation
for 80% of the application development; just like we did away with linking)
• More…
7. 2008 JavaOneSM
Conference | java.sun.com/javaone | 7
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java platform Ruby Compared
Using Java platform Ruby Together
Tools
Wrap Up Resources
8. 2008 JavaOneSM
Conference | java.sun.com/javaone | 8
How many of you
have already
worked with Ruby
and/or Rails?
Quick Poll
10. 2008 JavaOneSM
Conference | java.sun.com/javaone | 10
What is Ruby?
History
• Created by Yukihiro Matz Matsumoto
• Started working on Ruby on February 24, 1993
• Released it to the public in 1995
• Named so because of a joke, alluding to PERL's name
Can Be Used For
• Full-blown OO Applications (e.g. web applications, web services,
messaging, GUI, and much more!)
• Procedural scripting
Version
• 1.8.6 - latest stable (March 2008)
• 1.9 - with some major changes (coming soon)
Site: http://ruby-lang.org/
11. 2008 JavaOneSM
Conference | java.sun.com/javaone | 11
Notice
Dynamic
Types
Ruby Syntax Examples
Everything is an object
5.times {|i| puts Hello #{i} }
Array
a = [1, 'hi', 3.14, 1, 2]
a.reverse
a.each { |x| puts x }
Hash
h = {:water = 'wet', :fire = 'hot'}
h.each_pair do |key, value|
puts #{key} is #{value}
end
Ranges
(0..2).each {|i| puts i} #= [0, 1, 2]
('a'...'e').to_a #= [a, b, c, d]
12. 2008 JavaOneSM
Conference | java.sun.com/javaone | 12
Ruby Syntax Examples (cont’d)
Classes Methods
class Person
attr_accessor :name,
:age
def initialize(name,
age)
@name, @age = name,
age
end
end
...
p = Person.new(jay, 29)
p.name
jay”
Exceptions
raise ArgumentError,
Illegal arguments!”
...
begin
# Do something
rescue
# Handle exception
end
13. 2008 JavaOneSM
Conference | java.sun.com/javaone | 13
Ruby Syntax Examples (cont’d)
Returning multiple parameters
class MyClass
def mymethod
return 1, 2
end
end
a = MyClass.new
b, c = a.mymethod
Reflection
a = MyClass.new
a.public_methods
a.respond_to? mymethod
I/O
File.readlines('README').each do |line|
puts line
end
14. 2008 JavaOneSM
Conference | java.sun.com/javaone | 14
What is RubyGems?
Standard format for distributing Ruby programs/libraries
• Available gem server utility for serving gems from any machine
• Default gem server: rubyforge.org (as of March, 2008: 5,400+ projects)
• Install can automatically fetch dependencies
Sample commands
gem install rails
gem list --local
Sample gems we use:
• rails (yes, Rails is a gem)
• ferret (for searching)
• crypt (encrypted decrypting using a variety of ciphers)
• redcloth (text markup)
• glassfish_rails (discussed later in this presentation)
• Others: capistrano, deprec, rake, termios, etc.
Version - 1.0.1 (December, 2007)
Site: http://rubygems.org/
15. 2008 JavaOneSM
Conference | java.sun.com/javaone | 15
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java platform Ruby Compared
Using Java platform Ruby Together
Tools
Wrap Up Resources
16. 2008 JavaOneSM
Conference | java.sun.com/javaone | 16
What is Ruby on Rails?
Short names: Rails (or RoR)
A full-stack, web application, development framework:
• Web MVC framework
• Complex OR Mapping
• Unit testing
• Rake utility (similar to Ant, make, etc.)
• Database migrations
• AJAX/UI support (via prototype library)
• Web layouts (similar to DisplayTag, ValueList, etc.)
• Built-in web server
• Code generation (controllers, models, migration…)
• Support for 3rd-party plug-ins
• More…
Version: 2.0.x (Dec, 2007)
Site: http://rubyonrails.org/
17. 2008 JavaOneSM
Conference | java.sun.com/javaone | 17
Rails Basics
MVC Web Application Framework
• Action Pack: Controllers Views
• Active Record: Model
ActiveMailer (send emails)
Some built-in utilities
• script/server (Bundled web server)
• script/console (of Ruby’s “irb”)
• script/generate (generate code for controllers, model, views,
migrations, scaffold…)
• script/plugin (install 3rd-party plugins; e.g. incorporate in model
classes acts_as_ferret :fields = [ 'title', 'body' ])
• rake db:migrate (run migrations)
18. 2008 JavaOneSM
Conference | java.sun.com/javaone | 18
Sample Rails DB App in Minutes
One-time system-wide install of Rails framework
gem install rails
Generate application
rails -d mysql buapp
Edit config/database.yml (the only required config!)
development:
adapter: mysql
database: buapp_development
username: root
password:
Create database
rake db:create
Quick test via “scaffolding”
ruby script/generate scaffold Developer name:string
19. 2008 JavaOneSM
Conference | java.sun.com/javaone | 19
Sample Rails DB App in Minutes (cont’d)
Run migration script: rake db:migrate
Start bundled web server: ruby script/server
Access: http://localhost:3000/developers/
20. 2008 JavaOneSM
Conference | java.sun.com/javaone | 20
Sample Custom Rails Code
Model (app/models/developer.rb)
class Developer ActiveRecord::Base
has_many :tasks
belongs_to :team
validates_presence_of :name
end
Controller (app/controllers/show_controller.rb)
class ShowController ApplicationController
def index
@developers = Developer.find(:all, :order = name)
end
end
View (app/views/show/index.html.erb)
ol
% for developer in @developers %
li%= developer.name %/li
% end %
/ol
21. 2008 JavaOneSM
Conference | java.sun.com/javaone | 21
Typical Rails Development Activities
Generate/write models, controllers, and views:
• Models (e.g. one or many-to-many relationships, field validations,
methods)
• Custom “layouts” and CSS (for site/section wide consistent look-and-feel)
• Custom database code in controllers
• Custom “helpers” (code to use in views)
• Before/after controller “filters”
Add libraries/gems/plug-ins (e.g. ferret, crypt)
Configuration: environments/*.rb, routes.rb, etc.
Other: ActionMailer, stylesheets, javascripts, html/images…
22. 2008 JavaOneSM
Conference | java.sun.com/javaone | 22
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java platform Ruby Compared
Using Java platform Ruby Together
Tools
Wrap Up Resources
27. 2008 JavaOneSM
Conference | java.sun.com/javaone | 27
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java platform Ruby Compared
Using Java platform Ruby Together
Tools
Wrap Up Resources
28. 2008 JavaOneSM
Conference | java.sun.com/javaone | 28
How many of you
are already
working with
JRuby?
Quick Poll
29. 2008 JavaOneSM
Conference | java.sun.com/javaone | 29
Why Java Ruby/Rails Together?
The Java platform is a robust and time-tested technology
Rails is an elegant MVC framework for DB-web apps
JRuby brings the maturity of the Java platform to the world of
Ruby/Rails
Rails applications can be deployed in Java servers -- benefits include:
• a single container versus multiple instances of Mongrel
• out-of-box clustering and pooling features of many Java servers
• Organizations can maximize their existing investments in Java servers
• take advantage of Java platform features (e.g. Servlet Filters) or access Java
JARs/libraries (e.g. Google’s OpenSocial Shindig)
30. 2008 JavaOneSM
Conference | java.sun.com/javaone | 30
What is JRuby?
A 1.8.6 compatible Ruby interpreter written in 100% pure
Java platform
Most built-in Ruby classes provided
Support for interacting with and defining Java server
classes from within Ruby
Bean Scripting Framework (BSF) support
Distributed under a tri-license (CPL/GPL/LGPL)
A very active project:
• 1.1RC2 - Feb, 2008
• 1.0.3 - December, 2007
• 1.0 - June, 2007
• 0.9.9 - April, 2007
• 0.9.8 - March, 2007
31. 2008 JavaOneSM
Conference | java.sun.com/javaone | 31
Ways Java Platform Ruby Can Work
Together
Deploy Rails application In Java servers
• GoldSpike (WAR file)
• GoldSpike Rails Plugin
• Warbler (http://caldersphere.rubyforge.org/warbler/)
• The Grizzly Project (run Rails apps directly)
• Using the Grizzly project as a standalone (https://grizzly.dev.java.net)
• Inside GlassFish™ Project (https://glassfish.dev.java.net/)
Call Ruby from Java platform
• JRuby API
• Ruby ruby = Ruby.getDefaultInstance();
• IRubyObject result = ruby.evalScriptlet(1 + 1);
• Bean Scripting Framework (BSF)
• JSR-223: Scripting for the Java™ Platform
• Runtime.exec
Call Java server class from Ruby scripts using JRuby
32. 2008 JavaOneSM
Conference | java.sun.com/javaone | 32
Calling Java Server Classes in Ruby
jruby swingdemo.rb
require 'java'
parent = javax.swing.JFrame.new(Window)
chooser = javax.swing.JFileChooser.new()
return_val = chooser.showOpenDialog(parent)
if return_val == 0
puts chooser.getSelectedFile().getName()
end
parent.dispose
33. 2008 JavaOneSM
Conference | java.sun.com/javaone | 33
Calling Ruby from Java Platform
Using JRuby API
import org.jruby.*;
public class CallRuby
{
public static void main(String args[])
throws Exception
{
Ruby ruby = Ruby.getDefaultInstance();
String rubyScript = puts Ruby interpreted at
#{Time.now};
ruby.evalScript(rubyScript);
}
}
34. 2008 JavaOneSM
Conference | java.sun.com/javaone | 34
Call Ruby from Java Platform (cont’d)
Using Runtime.exec
public class RunRuby
{
public static void main(String args[])
throws Exception
{
Process p = Runtime.getRuntime().exec(ruby
+ args[0]);
BufferedReader br = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
p.waitFor();
System.out.println(rc = + p.exitValue());
}
}
35. 2008 JavaOneSM
Conference | java.sun.com/javaone | 35
Deploy Style #1: WAR File
Install JRuby and set JRUBY_HOME
Install gems under JRuby gems directory
jruby -S gem install rails activerecord-jdbc-
adapter -y --no-ri --no-rdoc
Generate Rails app (done earlier in our presentation)
Use JDBC™ technology in config/database.yml
development:
adapter: jdbc
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/buapp_development
username: root
password:
36. 2008 JavaOneSM
Conference | java.sun.com/javaone | 36
Deploy Style #1: WAR File (cont’d)
Install GoldSpike plugin for app
jruby script/plugin install
svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-
integration/plugins/goldspike
Creating, testing deploying WAR file
• jruby script/generate goldspike
• Copy required JAR files to WEB-INF/lib (e.g. mysql*.jar)
• Test app:
• jruby -S rake war:standalone:run
• http://localhost:8080/buapp/developers/
• Create WAR:
jruby -S rake war:standalone:create
• Deploy buapp.war to web server
(e.g. Tomcat’s webapps directory)
NOTE:
warbler is a
preferred
method but did
not support
Rails 2.0 at
time this
presentation
was developed
38. 2008 JavaOneSM
Conference | java.sun.com/javaone | 38
Deploy Style #3: glassfish_rails gem (cool!)
Install it: jruby -S gem install glassfish
Run it:
glassfish_rails hello
INFO: Listening on port 8080
Oct 8, 2007 11:13:01 PM
com.sun.enterprise.v3.services.impl.DeploymentService
postConstruct
INFO: Supported containers : web,phobos,jruby,php
Oct 8, 2007 11:13:01 PM
com.sun.enterprise.v3.server.AppServerStartup run
INFO: Glassfish v3 started in 1316 ms
Access it:
http://localhost:8080/
39. 2008 JavaOneSM
Conference | java.sun.com/javaone | 39
mod_proxy
Apache HTTP
Server (80)
Internet
DB
Mongrel/Rails
Server (8001)
Mongrel/Rails
Server (8002)
Mongrel/Rails
Server (8003)
Mongrel/Rails
Server (8004)
Mongrel Cluster
Internet
Tomcat or
other Java
App Server
DB
Apache HTTP
Server (80)
Java Server
Sample Configurations
40. 2008 JavaOneSM
Conference | java.sun.com/javaone | 40
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java Ruby Compared
Using Java Ruby Together
Tools
Wrap Up Resources
46. 2008 JavaOneSM
Conference | java.sun.com/javaone | 46
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java Ruby Compared
Using Java Ruby Together
Tools
Wrap Up Resources
47. 2008 JavaOneSM
Conference | java.sun.com/javaone | 47
Learning Ruby Rails
• Master Ruby before Rails (IMHO)
• Try small Ruby scripts, then classes, then more complex stuff (e.g.
mixins, modules), and so on…
• After spending a couple of days with Ruby, move on to Rails
For Rails
• Start with sample app and scaffold, then iteratively develop from
there (build app in increments)
• If something seems tough in Rails, you are probably doing it wrong
Other
• Use “irb” and “console” whenever possible
• Use capistrano for remote deployment
Recommendations
48. 2008 JavaOneSM
Conference | java.sun.com/javaone | 48
Online Resources
Official sites
• ruby-lang.org
• rubyonrails.org
• jruby.org
• netbeans.org
• glassfish.dev.java.net
Documentation
• ruby-doc.org
• railsbrain.com
Forums
• ruby-forum.com
• railsforum.com
Screencasts
• railscasts.com
• peepcode.com
Blogs
• headius.blogspot.com
• blogs.sun.com/arungupta/
Sample Real World Rails/JRuby sites
• mediacast.sun.com
• mix.oracle.com
Other
• 10 things every Java programmer
should know about Ruby -
onestepback.org/articles/10things/
49. 2008 JavaOneSM
Conference | java.sun.com/javaone | 49
Agenda
My Background BigUniverse.com
Core Ruby Technologies
Ruby on Rails
Java platform Ruby Compared
Using Java platform Ruby Together
Tools
Wrap Up Resources
50. 2008 JavaOneSM
Conference | java.sun.com/javaone | 50
Visit BigUniverse.com
to see a live demo of our site!
…and don’t hesitate to contact me:
anil@biguniverse.com
Thank You For Attending!