Class: Toq::Proxy

Inherits:
Object show all
Defined in:
lib/toq/proxy.rb

Overview

Maps the methods of remote objects to local ones.

You start like:

client = Toq::Client.new( host: 'localhost', port: 7331 )
bench  = Toq::Proxy.new( client, 'bench' )

And it allows you to do this:

result = bench.foo( 1, 2, 3 )

Instead of:

result = client.call( 'bench.foo', 1, 2, 3 )

The server on the other end must have an appropriate handler set, like:

class Bench
    def foo( i = 0 )
        return i
    end
end

server = Toq::Server.new( host: 'localhost', port: 7331 )
server.add_handler( 'bench', Bench.new )

Author:

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, handler) ⇒ Proxy

Returns a new instance of Proxy.

Parameters:

  • client (Client)
  • handler (String)


66
67
68
69
# File 'lib/toq/proxy.rb', line 66

def initialize( client, handler )
    @client  = client
    @handler = handler
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)

Used to provide the illusion of locality for remote methods.



78
79
80
# File 'lib/toq/proxy.rb', line 78

def method_missing( *args, &block )
    forward( *args, &block )
end

Class Method Details

.translate(method_name, &translator) ⇒ Object

Parameters:

  • method_name (Symbol)

    Method whose response to translate.

  • translator (Block)

    Block to be passed the response and return a translated object.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/toq/proxy.rb', line 46

def translate( method_name, &translator )
    define_method method_name do |*args, &b|
        # For blocking calls.
        if !b
            data = forward( method_name, *args )
            return data.rpc_exception? ?
                data : translator.call( data, *args )
        end

        # For non-blocking calls.
        forward( method_name, *args ) do |data|
            b.call( data.rpc_exception? ?
                        data : translator.call( data, *args ) )
        end
    end
end

Instance Method Details

#forward(sym, *args, &block) ⇒ Object



71
72
73
# File 'lib/toq/proxy.rb', line 71

def forward( sym, *args, &block )
    @client.call( "#{@handler}.#{sym.to_s}", *args, &block )
end