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.12. Creating a Shared "Whiteboard"

Credit: James Edward Gray II

Problem

You want to create the network equivalent of a whiteboard. Remote programs can place Ruby objects up on the board, examine objects on the board, or remove objects from the board.

Solution

You could just use a synchronized hash (as in Recipe 16.10), but Rinda[6] provides a data structure called a TupleSpace that is optimized for distributed programming. It works well when you have some clients putting data on the whiteboard, and other clients processing the data and taking it down.

Let's create an application that lets clients on different parts of the network translate each others' sentences, and builds a translation dictionary as they work.

It's easier to see the architecture of the server if you see the clients first, so here's a client that adds some English sentences to a shared TupleSpace:

	#!/usr/bin/ruby -w
	# english_client.rb
	require 'drb'
	require 'rinda/tuplespace'

	# Connect to the TupleSpace…
	DRb.start_service
	tuplespace = Rinda::TupleSpaceProxy.new(
	  DRbObject.new_with_uri('druby://127.0.0.1:61676')
	)

The English client's job is to split English sentences into words and to add each sentence to the whiteboard as a tuple: [unique id, language, words].

	counter = 0
	DATA.each_line do |line|
	  tuplespace.write([(counter += 1), 'English', line.strip.split])
	end

	__END__
	Ruby programmers have more fun
	Ruby gurus are obsessed with ducks
	Ruby programmers are happy programmers

Here's a second client. It creates a ...

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