O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.10. Sharing a Hash Between Any Number of Computers

Credit: James Edward Gray II

Problem

You want to easily share some application data with remote programs. Your needs are as trivial as, "What if all the computers could share this hash?"

Solution

Ruby's built-in DRb library can share Ruby objects across a network. Here's a simple hash server:

	#!/usr/local/ruby -w
	# 
drb_hash_server.rb
	require 'drb'

	# Start up DRb with a URI and a hash to share
	shared_hash = {:server => 'Some data set by the server' }
	DRb.start_service('druby://127.0.0.1:61676', shared_hash)
	puts 'Listening for connection…'
	DRb.thread.join # Wait on DRb thread to exit…

Run this server in one Ruby session, and then you can run a client in another:

	require 'drb'

	# Prep DRb
	DRb.start_service
	# Fetch the shared object
	shared_data = DRbObject.new_with_uri('druby://127.0.0.1:61676')

	# Add to the Hash
	shared_data[:client] = 'Some data set by the client'
	shared_data.each do |key, value|
	  puts "#{key} => #{value}"
	end
	# client => Some data set by the client
	# server => Some data set by the server

Discussion

If this looks like magic, that's the point. DRb hides the complexity of distributed programming. There are some complications (covered in later recipes), but for the most part DRb simply makes remote objects look like local objects.

The solution given above may meet your needs if you're working with a single server and client on a trusted network, but applications aren't always that simple. Issues like thread-safety and security ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required