]> git.saurik.com Git - redis.git/blob - client-libraries/ruby_2/rubyredis.rb
Initial version of an alternative Ruby client added
[redis.git] / client-libraries / ruby_2 / rubyredis.rb
1 # RubyRedis is an alternative implementatin of Ruby client library written
2 # by Salvatore Sanfilippo.
3 #
4 # The aim of this library is to create an alternative client library that is
5 # much simpler and does not implement every command explicitly but uses
6 # method_missing instead.
7
8 require 'socket'
9
10 class RedisClient
11 BulkCommands = {
12 "set"=>true, "setnx"=>true, "rpush"=>true, "lpush"=>true, "lset"=>true,
13 "lrem"=>true, "sadd"=>true, "srem"=>true, "sismember"=>true,
14 "echo"=>true, "getset"=>true, "smove"=>true
15 }
16
17 def initialize(opts={})
18 opts = {:host => 'localhost', :port => '6379', :db => 0}.merge(opts)
19 @host = opts[:host]
20 @port = opts[:port]
21 @db = opts[:db]
22 @sock = connect_to_server
23 end
24
25 def to_s
26 "Redis Client connected to #{@host}:#{@port} against DB #{@db}"
27 end
28
29 def connect_to_server
30 TCPSocket.new(@host, @port, 0)
31 end
32
33 def method_missing(*argv)
34 call_command(argv)
35 end
36
37 def call_command(argv)
38 bulk = nil
39 argv[0] = argv[0].to_s.downcase
40 if BulkCommands[argv[0]]
41 bulk = argv[-1]
42 argv[-1] = bulk.length
43 end
44 @sock.write(argv.join(" ")+"\r\n")
45 @sock.write(bulk+"\r\n") if bulk
46 read_reply
47 end
48
49 def read_reply
50 line = @sock.gets
51 case line[0..0]
52 when "-"
53 raise line.strip
54 when "+"
55 line[1..-1].strip
56 when ":"
57 line[1..-1].to_i
58 when "$"
59 bulklen = line[1..-1].to_i
60 return nil if bulklen == -1
61 data = @sock.read(bulklen)
62 @sock.read(2) # CRLF
63 data
64 when "*"
65 objects = line[1..-1].to_i
66 return nil if bulklen == -1
67 res = []
68 objects.times {
69 res << read_reply
70 }
71 res
72 end
73 end
74 end