Initialization in Ruby

Every Ice-based application needs to initialize the Ice run time, and this initialization returns an Ice::Communicator object.

Communicator is a local Ruby object that represents an instance of the Ice run time. Most Ice-based applications create and use a single Communicator object, although it is possible and occasionally desirable to have multiple Communicator objects in the same application.

You initialize the Ice run time by calling  Ice::initialize, for example:

Ruby
require 'Ice'

communicator = Ice::initialize(ARGV)

Ice::initialize accepts the argument list that is passed to the program by the operating system. The function scans the argument list for any command-line options that are relevant to the Ice run time; any such options are removed from the argument list so, when Ice::initialize returns, the only options and arguments remaining are those that concern your application. If anything goes wrong during initialization, initialize throws an exception.

Before leaving your program, you must call Communicator.destroy. The destroy method is responsible for finalizing the Ice run time. In particular,  destroy ensures that any outstanding threads are joined with and reclaims a number of operating system resources, such as file descriptors and memory. Never allow your program to terminate without calling destroy first.

The general shape of our Ice Ruby application is therefore:

Ruby
require 'Ice'
begin
    communicator = Ice::initialize(ARGV)
    ...
ensure
    if defined? communicator and communicator != nil
        communicator.destroy()
    end
end

This code is a little bit clunky, as we need to make sure the communicator gets destroyed in all paths, including when an exception is thrown.

Fortunately, the Ice::initialize function accepts an optional block: if provided, initialize will create a communicator, pass it to the block, destroy the communicator automatically when the block completes, and return the block's result as the result of initialize.

The preferred way to initialize the Ice run time in Ruby is therefore:

Ruby
require 'Ice'
Ice::initialize(ARGV) do |communicator, args|
    ...
end

initialize requires the block to accept one or two arguments: if the block accepts only one argument, initialize passes the communicator, otherwise initialize passes the communicator and the filtered argument vector.

See Also