Eran's blog

Rails, meet Java

Most of the backend at work is done using a behemoth of a Java server so it’s pretty hard to avoid cooperating with that no matter what language or what application I’m writing. Right now, it so happens, I’m working on a Rails application that acts as a frontend to an app managed by said java server. My first few weeks on this project consisted mostly of getting java and ruby to play well together.

I started out by adding an XML-RPC layer to our existing services. This wasn’t too hard, there’s a selection of XML-RPC libs for Java with pretty solid implementations. Creating a Rails XML-RPC client was even easier but when my API class started to grow over to 20 methods I decided that a different solution is in order.

Not too long ago, Assaf mentioned ActiveRevver in one of his posts and it seemed like that might be a good place to start. ActiveRevver creates an ActiveRecord-like layer on top of the revver’s web services and that’s exactly what I wanted for myself. A clean interface, similar to ActiveRecord’s that plays well with Rails.

Following ActiveRevver’s example, my models are based on OpenStruct which makes it easy to define objects on the fly (unless, of course, you want to have a method name type). method_missing takes care of delegating member access to the underlying @attributes Ostruct object.

class ActiveFoo::Base
def initialize(attrs = {}, opts = {})
@new_record = opts[:record_from_api] ? false : true

def initialize_attributes!(attrs)
@attributes = OpenStruct.new(attrs.stringify_keys!)

class ActiveFoo::Account '',
'password' => '',
'email' => '',
'validated' => false
super(schema.merge(attrs), opts)

A very cool feature in ActiveRevver is their implementation of Associations. Using has_many you can add association just like you would with ActiveRecord. This uses the CollectionProxy class which wraps an array of hashes and presents it as a collection of items of the related class. A sprinkling of find and find_by_foo methods later and this feels just like using ActiveRecord.

One thing I needed to do that I’m not sure ActiveRevver supports was store my objects in a session. To do that, classes must be marshallable. This is easily achieved by adding the marshal_load and marshal_dump methods.

def marshal_dump
[@attributes, new_record?]

def marshal_load(obj)
@attributes = obj[0]
@new_record = obj[1]

I can now almost completely ignore my Java backend and pretend my application is Ruby and Rails all the way.


Filed under: Ruby on Rails

%d bloggers like this: