50
From Java To Ruby … and Back Anil Hemrajani, Founder, BigUniverse.com TS-4868, [email protected]

From Java To Ruby … and Back - Oracle · • Custom apps & products - AT&T, ... Sample commands gem install rails gem list --local ... Call Ruby from Java platform

  • Upload
    lamque

  • View
    227

  • Download
    1

Embed Size (px)

Citation preview

From Java To Ruby … and Back

Anil Hemrajani, Founder, BigUniverse.com

TS-4868, [email protected]

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

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

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”

2008 JavaOneSM Conference | java.sun.com/javaone | 5

Big Universe Website & Products

WebsiteBooks, 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

2008 JavaOneSM Conference | java.sun.com/javaone | 6

Why We Chose Ruby?

Primarily because of the Rails frameworkI 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 farRapid 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…

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

2008 JavaOneSM Conference | java.sun.com/javaone | 8

How many of you have already

worked with Ruby and/or Rails?

Quick Poll

2008 JavaOneSM Conference | java.sun.com/javaone | 9

RubyGems�gem �Rails (gem)

RUBY INTERPRETER

�gem �gem

The Basics

Ruby Interpreter

Ruby Libraries and/or Gems

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/

2008 JavaOneSM Conference | java.sun.com/javaone | 11

Notice Dynamic

Types

Ruby Syntax Examples

Everything is an object5.times {|i| puts "Hello #{i}" }

Arraya = [1, 'hi', 3.14, 1, 2]a.reversea.each { |x| puts x }

Hashh = {: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"]

2008 JavaOneSM Conference | java.sun.com/javaone | 12

Ruby Syntax Examples (cont’d)

Classes & Methods

class Personattr_accessor :name, :age

def initialize(name, age)@name, @age = name, age

endend...p = Person.new("jay", 29)p.name>> "jay”

Exceptions

raise ArgumentError, "Illegal arguments!”

...begin

# Do somethingrescue

# Handle exceptionend

2008 JavaOneSM Conference | java.sun.com/javaone | 13

Ruby Syntax Examples (cont’d)

Returning multiple parametersclass MyClass

def mymethodreturn 1, 2

endenda = MyClass.newb, c = a.mymethod

Reflectiona = MyClass.newa.public_methodsa.respond_to? "mymethod"

I/OFile.readlines('README').each do |line|

puts lineend

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 commandsgem install railsgem 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/

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

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/

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)

2008 JavaOneSM Conference | java.sun.com/javaone | 18

Sample Rails DB App in Minutes

One-time system-wide install of Rails frameworkgem install rails

Generate applicationrails -d mysql buapp

Edit config/database.yml (the only required config!)development: adapter: mysql database: buapp_development username: root password:

Create databaserake db:create

Quick test via “scaffolding”ruby script/generate scaffold Developer name:string

2008 JavaOneSM Conference | java.sun.com/javaone | 19

Sample Rails DB App in Minutes (cont’d)

Run migration script: rake db:migrateStart bundled web server: ruby script/serverAccess: http://localhost:3000/developers/

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 :nameend

Controller (app/controllers/show_controller.rb)class ShowController < ApplicationController def index @developers = Developer.find(:all, :order => "name") endend

View (app/views/show/index.html.erb)<ol> <% for developer in @developers %> <li><%= developer.name %></li> <% end %></ol>

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…

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

2008 JavaOneSM Conference | java.sun.com/javaone | 23

Comparing Java Platform & Ruby

Syntax

Conventions

Benchmarks

2008 JavaOneSM Conference | java.sun.com/javaone | 24

Syntax

import java.sql.*;

public class LoadFileIntoDB {public int doLoad(String fileName) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileName));

...}

require 'mysql'

class LoadFileIntoDB def do_load(file_name) f = File.open file_name ... end

2008 JavaOneSM Conference | java.sun.com/javaone | 25

myclass.rbMyClass.javaFile name

MyClassMyClassClass

my_methodmyMethodMethod

my_variablemyVariableVariables

MIN_LENGTHMIN_LENGTHConstant

=beginsome code=end

/* */ or /** */Block Comments

#//Single-line Comments

RubyJava

Code Conventions

2008 JavaOneSM Conference | java.sun.com/javaone | 26

223.64230.843Database (insert/fetch 10 thousand rows)

1.4694.641Socket (download 1MB file)

17.4375.75File I/O (write/read 1 million lines)

13.7660.125Loops (100 million times)

0.0160.046Threads (spawn 100)

Ruby(sec)

Java(sec)

Function

Code/Details available at: http://visualpatterns.com/javaruby.php

(Amateur) Benchmarks

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

2008 JavaOneSM Conference | java.sun.com/javaone | 28

How many of you are already working with

JRuby?

Quick Poll

2008 JavaOneSM Conference | java.sun.com/javaone | 29

Why Java & Ruby/Rails Together?

The Java platform is a robust and time-tested technologyRails is an elegant MVC framework for DB-web appsJRuby brings the maturity of the Java platform to the world of Ruby/RailsRails 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)

2008 JavaOneSM Conference | java.sun.com/javaone | 30

What is JRuby?

A 1.8.6 compatible Ruby interpreter written in 100% pure Java platformMost built-in Ruby classes providedSupport for interacting with and defining Java server classes from within RubyBean Scripting Framework (BSF) supportDistributed 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

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

2008 JavaOneSM Conference | java.sun.com/javaone | 32

Calling Java Server Classes in Ruby

jruby swingdemo.rbrequire '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()endparent.dispose

2008 JavaOneSM Conference | java.sun.com/javaone | 33

Calling Ruby from Java Platform

Using JRuby APIimport 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); }}

2008 JavaOneSM Conference | java.sun.com/javaone | 34

Call Ruby from Java Platform (cont’d)

Using Runtime.execpublic 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()); }}

2008 JavaOneSM Conference | java.sun.com/javaone | 35

Deploy Style #1: WAR File

Install JRuby and set JRUBY_HOMEInstall gems under JRuby gems directoryjruby -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.ymldevelopment: adapter: jdbc driver: com.mysql.jdbc.Driver url: jdbc:mysql://localhost/buapp_development username: root password:

2008 JavaOneSM Conference | java.sun.com/javaone | 36

Deploy Style #1: WAR File (cont’d)

Install GoldSpike plugin for appjruby 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

2008 JavaOneSM Conference | java.sun.com/javaone | 37

Install GlassFish v3, Technology Preview 1: java -jar glassfish*.jar

Run server: java -jar lib/glassfish*SNAPSHOT.jar (from glassfish directory)

Deploy sample app:glassfish/bin/asadmin deploy --path hello

Access it: http://localhost:8080/hello/

Deploy Style #2: Directly With GlassFish v3

Source: http://blogs.sun.com/arungupta/entry/ first_jruby_on_rails_app

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 8080Oct 8, 2007 11:13:01 PM

com.sun.enterprise.v3.services.impl.DeploymentService postConstruct

INFO: Supported containers : web,phobos,jruby,phpOct 8, 2007 11:13:01 PM

com.sun.enterprise.v3.server.AppServerStartup runINFO: Glassfish v3 started in 1316 ms

Access it: http://localhost:8080/

2008 JavaOneSM Conference | java.sun.com/javaone | 39

mod_proxyApache HTTP

Server (80)Internet DB

Mongrel/Rails Server (8001)

Mongrel/Rails Server (8002)

� Mongrel/Rails Server (8003)

Mongrel/Rails Server (8004)

Mongrel Cluster

InternetTomcat or other Java App Server DB

Apache HTTP Server (80)

Java Server

Sample Configurations

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

2008 JavaOneSM Conference | java.sun.com/javaone | 41

Tools

IDEs & Editors

Capistrano (automate application deployment)

Handy command-line utilities

2008 JavaOneSM Conference | java.sun.com/javaone | 42

NetBeans Ruby Pack Software

code highlighting & completion,

debugger, refactoring…

2008 JavaOneSM Conference | java.sun.com/javaone | 43

Eclipse With RDT or Aptana/RadRails

2008 JavaOneSM Conference | java.sun.com/javaone | 44

Capistrano: Automate App Deployment

apache_installapache_restartchange_root_passworddeploydeploy_with_migrationsdisable_webenable_webexecute_mysqlinstall_apacheinstall_gemsinstall_phpinstall_postfixinstall_rails_stackinstall_rmagickinstall_rubygems

restart_apacherestart_apprestart_mongrel_clustersetup_admin_account_as_rootsetup_mysqlsetup_scmsetup_smtp_serversetup_ssh_keysstart_apachestart_appstart_mongrel_clusterstop_apachestop_mongrel_clustertrac_installMany others…

Partial List of Tasks (can also write custom tasks)

2008 JavaOneSM Conference | java.sun.com/javaone | 45

Handy Command-Line Utilities$ irbirb(main):001:0> Time.now=> Sun Sep 30 19:47:55 -0400 2007irb(main):002:0>

$ script/consoleLoading development environment.>> Blog.find(:all)

$ ri String----------------------------------------------------A +String+ object holds and manipulates ...Includes:--------- Comparable(<, <=, ==, >, >=, between?) Enumerable(all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries,

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

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

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/

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

2008 JavaOneSM Conference | java.sun.com/javaone | 50

Visit BigUniverse.comto see a live demo of our site!

…and don’t hesitate to contact me:[email protected]

Thank You For Attending!