Class: Gibson::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Client

Create a new Gibson::Client instance, the options are passed to Gibson::Connection initialize method.



20
21
22
23
# File 'lib/gibson/gibson.rb', line 20

def initialize(opts = {})
  @connection = nil
  @options = opts
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments) ⇒ Object

This method will be called for every undefined method call of Gibson::Client mapping the method to its opcode and creating its argument payload. For instance a call to:

client = Gibson::Client.new
client.set 0, 'foo', 'bar'

Will be executed as:

client.query Protocol::COMMANDS[:set], '0 foo bar'


112
113
114
115
116
# File 'lib/gibson/gibson.rb', line 112

def method_missing(name, *arguments)
  if Protocol::COMMANDS.has_key? name 
    query Protocol::COMMANDS[name], arguments.join(' ')
  end
end

Instance Method Details

#connectObject

Create the connection.



27
28
29
30
# File 'lib/gibson/gibson.rb', line 27

def connect
  @connection = Connection.new( @options )
  @connection.connect
end

#query(opcode, payload = '') ⇒ Object

Send a query to the server given its opcode and arguments payload. Return the decoded data, or raise one of the RuntimeErrors defined inside Gibson::Protocol.



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/gibson/gibson.rb', line 89

def query( opcode, payload = '' )
  connect if @connection == nil or not @connection.connected?

  psize  = payload.length
  packet = [ 2 + psize, opcode, payload ].pack( 'L<S<Z' + psize.to_s )

  @connection.write packet

  code, encoding, size = @connection.read(7).unpack('S<cL<' )
  data = @connection.read size

  decode code, encoding, size, StringIO.new(data)
end