Class: Zack::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/zack/client.rb

Overview

Client for a simple client-server RPC connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tube_name, opts = {}) ⇒ Client

Constructs a client for the service given by tube_name.

Parameters:

  • tube_name (String)

    the tube to communicate with

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :server (String)

    beanstalkd server location url

  • :only (Array<Symbol>)

    ignores all messages not in this hash

  • :with_answer (Array<Symbol>)

    these messages wait for an answer from the service

  • :timeout (Fixint)

    How long to wait for an answer



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/zack/client.rb', line 18

def initialize(tube_name, opts={})
  # Only respond to these messages
  @only        = opts[:only] || proc { true }
  # These have answers (wait for the server to answer)
  @with_answer = opts[:with_answer] || []
  @timeout     = opts[:timeout]
  
  @tube_name  = tube_name
  @server     = opts[:server] || 'localhost:11300'

  connect
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/zack/client.rb', line 42

def method_missing(sym, *args, &block)
  super unless respond_to?(sym)
 
  raise ArgumentError, "Can't call methods remotely with a block" if block

  if has_answer?(sym)
    with_timeout do
      return service.call([sym, args])
    end
  else
    service.notify [sym, args]
    return nil
  end
  
rescue Cod::ConnectionLost
  # Don't resend, just reconnect. This might loose one or two messages, 
  # but we don't make such guarantees at this protocol level.
  reconnect
  
  raise Zack::AnswerLost
  
rescue Timeout::Error => ex
  raise Zack::ServiceTimeout, 
    "The service took too long to answer (>#{@timeout || 1}s)."
end

Instance Attribute Details

#serviceObject (readonly)

Returns the value of attribute service.



7
8
9
# File 'lib/zack/client.rb', line 7

def service
  @service
end

Instance Method Details

#closeObject



68
69
70
# File 'lib/zack/client.rb', line 68

def close
  @service.close
end

#has_answer?(sym) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/zack/client.rb', line 37

def has_answer?(sym)
  @with_answer.include?(sym.to_sym)
end

#respond_to?(msg) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/zack/client.rb', line 32

def respond_to?(msg)
  !! @only[msg]
end