If you find this useful, you might like my other articles , too.

This tutorial shows how to use distributed ruby to connect a rails application with another ruby service not running inside Rails.

Distributed Ruby (DRb)

I won’t waste time here explaining how to use DRb. Just a short example from Rubycentral with a very simple server:

require 'drb' class TestServer def doit "Hello, Distributed World" end end aServerObject = TestServer.new DRb.start_service('druby://localhost:9000', aServerObject) DRb.thread.join # Don't exit just yet!

and an even simpler client:

require 'drb' DRb.start_service obj = DRbObject.new(nil, 'druby://localhost:9000') # Now use obj puts obj.doit

Active Record

As you want to connect the DRb Server to Rails, you probably want to use your model classes, too. Just include them (I’m still looking for a simple way to automagically include all models) and configure ActiveRecord:

require 'drb' require 'rubygems' require_gem 'activerecord' require 'app/models/user.rb' class Server def dump puts User.find(:first).inspect end end ActiveRecord::Base.establish_connection( :adapter => "mysql", :username => "xxxx", :host => "localhost", :password => "xxxx", :database => "xxxx" ) DRb.start_service("druby://localhost:9000", Server.new) puts DRb.uri DRb.thread.join

Don’t repeat yourself!

Repeating the database configuration as I did in the above example is soooo against The Ruby Way. A better way is to parse config/database.yml and use the result to configure ActiveRecord. This has the added benefit of being able to use different database setups:

require 'drb' require 'rubygems' require 'yaml' require_gem 'activerecord' require 'app/models/user.rb' class Server def dump puts User.find(:first).inspect end end abort "usage: #{__FILE__} environment" unless ARGV[0] database_yaml = YAML.load_file("config/database.yml") abort "environment '#{ARGV[0]}' not found" unless database_config = database_yaml[ARGV[0]] ActiveRecord::Base.establish_connection(database_config) DRb.start_service("druby://localhost:9000", Server.new) puts DRb.uri DRb.thread.join

From Rails?

Just use the simple client from above inside your model or controller without special changes for Rails. Yes, it’s that simple. Enjoy!

require 'drb' ... class DrbController < ApplicationController def get_user_via_drb DRb.start_service obj = DRbObject.new(nil, 'druby://localhost:9000') @user = obj.dump end

Here is a short thread about problems with DRb.

DRb over unix sockets

Brian has a nice writeup how to use DRb over unix sockets – it’s extremly easy, just change the URI et voila…

[tags]ruby, rails, drb[/tags]