views:

218

answers:

1

I'm fairly new to (J)Ruby - have written a few tiny "demo apps" in RoR but haven't really gotten right into the syntax though.

I have an app at the moment written in Java that takes an XML file, parses it and then inserts it into a MySQL database using Hibernate. What I'd really like to do is see if I can port this to JRuby, - mainly as a learning exercise - but I'm not really sure where to start.

This document seems to give a good idea on parsing the XML:

http://developer.yahoo.com/ruby/ruby-xml.html

But from there, I'm not sure what the best way to put it in the DB is. Would ActiveRecord be an option, and if so how do I hook it in to a "standalone" JRuby app? Or I guess I could somehow integrate my existing Hibernate stuff with it, right?

Any advice or links to sample code would be gratefully received...

Regards, Andrew.

+4  A: 

Go ahead and take the ActiveRecord plunge, here is some getting started for the h2 embedded java database.

I think you need these gems

jruby -S gem install active_record
jruby -S gem install active_record_jdbc_adapter
jruby -S gem install active_record_jdbch2_adapter
jruby -S gem install jdbc_h2

Then you can use active record like this

require 'active_record'
require 'logger'

my_logger = Logger.new(STDOUT)
my_logger.level = Logger::DEBUG
ActiveRecord::Base.logger = my_logger

ActiveRecord::Base.establish_connection(
  :adapter => 'jdbch2',
  :database => "my_database_file",        # set to anything you want first run
  :username => "my_username",             # set to anything you want first run
  :password => "my_secret_password"       # set to anything you want first run
)

You will need to have some tables to insert into. In keeping in ActiveRecord convention, maintain a folder of sequenced database schema changes, and then point the migrator to that folder. For example create the a "migrations" folder, and the following file named "20090815230000_create_my_models.rb". Be sure the "snake_case" file name matches the CamelCase class name.

class CreateMyModels < ActiveRecord::Migration
  def self.up
    create_table :my_models do |t|
      t.string  :foo
    end
  end

  def self.down
    drop_table :my_models
  end
end

Now (returning to your main script) you can point the Rails migrator to this folder. The rails migrator stores all the meta data necessery to run the migrations in order, and run the new ones once they become available.

ActiveRecord::Migration.verbose = true
ActiveRecord::Migrator.migrate("migrations")

Once you've created your tables you can use ActiveRecord as normal

class MyModel < ActiveRecord::Base
end

Now you can insert stuff into the database.

x=MyModel.new
x.foo="bar"
x.save!

I hope this helps. If ActiveRecord is too much of a pain to get working, Sequel is light and fun.

jrhicks
cool, same works for mysql, just gem install jdbc-mysql, and in the driver section put jdbcmysql
khelll