Why would a Java shop want to use Ruby?

Preview:

DESCRIPTION

Briefly explores several practical reasons that may encourage Java shops to explore Ruby.

Citation preview

Why would a Java Shop want to use Ruby?

Keith Pitty

Open Source Developers’ ConferenceBrisbane

29 November 2007

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

About Keith• Programming professionally since 1983

• Early experience on mainframes

• Smalltalk was my first OO language

• Employed by a Java consultancy since 2000

• Fascinated by Ruby and Rails since 2004

• Enjoy sampling a wide range of beers

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java

public class print { public static void main(String[] args) { System.out.println("Hi, I'm Java"); }}

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby

#!/usr/bin/env ruby

puts "Hi, I'm Ruby"

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

No!!!• This is not a language war!

• Java and Ruby both have their strengths

• I’m not interested in Ruby “beating” Java

• The question is:

• Can Ruby help Java programmers?

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java

• Most popular language (21.7%)

• TIOBE PCI, September 2007

• Mature platform

• Trusted in the “enterprise”

• Has reached a plateau

• “The new COBOL”

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby• Tenth most popular language (2.1%)

• Marked increase in popularity since mid-2006 due to Ruby on Rails

• Matz’s original motivation:

• a scripting language

• more powerful than Perl

• more object-oriented than Python

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Why Ruby? (Quote Part 1)

“I don’t believe there would be any real technical benefit. There may be a productivity boost, but when

you consider how much time is used by developers, QA, etc... to bring in a new technology, chances are the net

[benefit] won’t be that great.”

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Why Ruby?(Quote Part 2)

“I think the best argument for Ruby is that your developers want it. If the developers are

yearning for new technology, it’s probably worth considering. Happy developers code

more and code better.”

Norman Richards, JBoss

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Perspectives

• Vendors

• Open source contributors

• Managers

• Business owners

• Developers

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby: Why not?

• How widespread is knowledge of Ruby within the Java community?

• In my experience, there is limited awareness

• On the other hand:

• Ruby may have benefits that are complementary to Java

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Potential Ruby Benefits

• Ruby skills may complement Java skills

• Learning Ruby may be interesting, broadening a programmer’s thinking

• Happier programmers

• Quicker time to market

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Enough Preamble

• What does Ruby have to offer people in Java development shops?

• Let’s explore some specifics...

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby Scripts

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby Scripts• Scripts help with repetitive tasks

• Shell scripts, SQL scripts, Ant scripts

• Sometimes the logic lends itself to a general purpose language

• Can run a Java application via a shell script

• A Ruby script is interpreted directly and is more concise

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby Script Example

• Deleting files within a given directory according to given criteria

• e.g. older than a given time

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby Script Example*#!/usr/bin/env rubydef delete_if(dir) Dir.chdir(dir) do Dir.foreach(*.*) do |entry| next if File.stat(entry).directory? if yield entry File.unlink(entry) end end endend

delete_if("/tmp") { |f| File.mtime(f) < Time.local(2007,10,29,0,0,0) }

* See Hal Fulton’s “The Ruby Way”

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Rake and Internal DSLs

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Rake

• Ruby-based build language

• Developed by Jim Weirach

• Similar to make and ant

• An internal Domain Specific Language

• make and ant are external DSLs

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Regular Rake Taskstask :init do # init actions end

task :compile => [:init] do # compile actionsend

task :build => [:init, :compile] do # build actionsend

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Extending Rake*def copyTask srcGlob, targetDirSuffix, taskSymbol targetDir = File.join BUILD_DIR, targetDirSuffix mkdir_p targetDir, QUIET FileList[srcGlob].each do |f| target = File.join targetDir, File.basename(f) file target => [f] do |t| cp f, target end task taskSymbol => target endend

copyTask 'articles/*.gif', 'articles', :articles

* see Martin Fowler’s rake article

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Internal DSLs

• Other Ruby internal DSLs:

• buildr

• capistrano

• ...

• create your own!

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Buildr

• a build system for Java apps

• encompasses Maven and Ant

• written in Ruby

• based on Rake

• uses Antwrap to configure and run Ant tasks

• extensible in Ruby

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Capistrano• Created by Jamis Buck

• Originally to “ease the pain of deploying Rails applications”

• Exposes simple commands

• Once project has been “capified”

• $ cap deploy

• Useful beyond Rails

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Capistrano Example

desc "Copy production database config file."namespace :deploy do task :after_update_code, :roles => :app do db_config = "#{shared_path}/config/database.yml.production" run "cp #{db_config} #{release_path}/config/database.yml" end end

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Metaprogramming

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Metaprogramming• Very powerful feature of Ruby

• Dynamic programming

• Methods: method_missing, define_method, module_eval, class_eval, instance_eval, self.included, self.inherited, extend

• Callable objects: procs, lambdas, blocks

• Modifying the singleton class: class <<

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

method_missingclass Roman def roman_to_int(str) # ... end def method_missing(methId) str = methId.id2name roman_to_int(str) endend

r = Roman.newr.iv #=> 4r.xxiii #=> 23r.mm #=> 2000

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

More Examples?

• Open source Ruby frameworks

• e.g. Ruby on Rails web application framework

• many examples of metaprogramming to be found in the Rails source code

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby on Rails

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Ruby on Rails

• Web application framework released by David Heinemeier Hansson in 2004

• Extracted from the Basecamp application

• The killer app for Ruby

• “Convention over Configuration”

• Code generators

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Rails Example

$ rails beers

Creates directory structure for new project

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Generating a Resource

$ ./script/generate scaffold_resource beer name:string

Creates a model, a controller, and a set of templates that's ready to use as the starting point for your REST-like, resource-oriented application.

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Migrationclass CreateBeers < ActiveRecord::Migration def self.up create_table :beers do |t| t.column :name, :string end end

def self.down drop_table :beers endend

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Running Migrations

$ rake db:migrate

== CreateBeers: migrating =====================================================-- create_table(:beers) -> 0.0735s== CreateBeers: migrated (0.0737s) ============================================

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Model

class Beer < ActiveRecord::Base has_many :votesend

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

View (new.rhtml)<h1>New beer</h1>

<%= error_messages_for :beer %>

<% form_for(:beer, :url => beers_path) do |f| %> <p> <b>Name</b><br /> <%= f.text_field :name %> </p>

<p> <%= submit_tag "Create" %> </p><% end %>

<%= link_to 'Back', beers_path %>

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Controllerclass BeersController < ApplicationController

def new @beer = Beer.new end

def create @beer = Beer.new(params[:beer]) respond_to do |format| if @beer.save flash[:notice] = 'Beer was successfully created.' format.html { redirect_to beer_url(@beer) } else format.html { render :action => "new" } end end end end

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

More about Rails

• There’s much more about Rails to explore

• But that’s another topic

• We’ve touched upon some appealing aspects

• Development is much quicker!

• But ...

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java Perspective

• What if ...

• Java provides where Ruby doesn’t?

• What about ...

• deploying Rails apps?

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java and Ruby

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

JRuby

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

JRuby

• Java implementation of Ruby

• Major advantages:

• Java libraries can be used with Ruby syntax

• Deploy Rails apps on Java app servers

• via WAR files

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Invoking Java from Rubyrequire 'java'

m = java.util.HashMap.new

m.put "Stream", "Ruby"m.put "Topic", "JRuby"

iter = m.keySet.iteratorwhile iter.hasNext key = iter.next puts "#{key}=#{m.get(key)}"end

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Some JRuby Capabilities

• Implement Java interfaces via import or impl

• Extend Java classes

• Use Ruby methods on Java collections courtesy of Ruby mixins

• Use JavaUtilities.extend_proxy to add methods to Java types

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Java DOM and XSLT*require 'java' require 'stringio'

TransformerFactory = javax.xml.transform.TransformerFactory StreamSource = javax.xml.transform.stream.StreamSource StreamResult = javax.xml.transform.stream.StreamResult

f = TransformerFactory.new_instance t = f.new_transformer StreamSource.new(java.io.FileReader.new(ARGV[1])) s = StringIO.new t.transform StreamSource.new(java.io.FileReader.new(ARGV[0])), StreamResult.new(org.jruby.util.IOOutputStream.new(s)) puts s.string

* see Ola Bini’s book

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

JRuby on Rails

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

JRuby on Rails: JDBC

• Download JDBC driver

• Add to CLASSPATH

• Configure config/database.yml

• Update config/environment.rb

development: adapter: jdbc driver: com.mysql.jdbc.Driver url: jdbc:mysql://localhost/beers_development username: test password: test

require 'jdbc_adapter'

Rails::Initializer.run do |config|

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

• Option 1:

• Pack of Mongrels inside one JVM

• Option 2:

• Bundle as WAR and deploy inside Tomcat

Deploying JRuby on Rails Applications

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Pack of Mongrels

• Familiar to Rails developers

• Install mongrel_jcustler Gem

• Configure pack using mongrel_rails

• Start pack using mongrel_rails

• Configure load balancing proxy support and virtual host in Apache

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Deploying via a WAR

• Install GoldSpike plug-in in Rails app

• Configure app with correct driver for JDBC connections (in config/war.rb)

• Use jruby rake task to create WAR

• Deploy WAR

• Configure Apache

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Installing GoldSpike

jruby script/plugin install -x svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-integration/plugins/goldspike

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

JDBC Driver Config

maven_library 'mysql', 'mysql-connector-java', '5.0.4'

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Create WAR

jruby -S rake war:standalone:create

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Deploy WAR

cp beers.war $TOMCAT_HOME/webapps

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Conclusion

• Ruby offers some interesting benefits

• Ruby on Rails offers quick development for CRUD web apps

• JRuby enables Ruby apps to call Java code

• JRuby enables deployment of Rails apps via WAR files to Java app servers

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Resources• Ola Bini. Practical JRuby on Rails Web

2.0 Projects. Apress, 2007

• David A. Black. Ruby for Rails. Manning, 2006

• http://buildr.rubyforge.org

• http://www.capify.org

• http://jruby.codehaus.org

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Resources (ctd.)

• Martin Fowler. RailsConf2007 => http://martinfowler.com/bliki/RailsConf2007.html

• Martin Fowler. Using the Rake Build Language => http://martinfowler.com/articles/rake.html

• Hal Fulton. The Ruby Way. Addison-Wesley, 2007

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Resources (ctd)

• David Heinemeier Hansson. Sun surprises at RailsConf Europe 2007 => http://www.loudthinking.com/posts/11-sun-surprises-at-railsconf-europe-2007

• Brian Marick. Everyday Scripting with Ruby: For Teams, Testers and You. Pragmatic Programmers, 2006

Why would a Java Shop want to use Ruby? Keith Pitty OSDC, 29 November 2007

Thanks for listening!

http://keithpitty.com