]> git.saurik.com Git - redis.git/blob - client-libraries/ruby_2/rubyredis.rb
RubyRedis: Array alike operators implemented
[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 call_command(["select",@db]) if @db != 0
24 end
25
26 def to_s
27 "Redis Client connected to #{@host}:#{@port} against DB #{@db}"
28 end
29
30 def connect_to_server
31 TCPSocket.new(@host, @port, 0)
32 end
33
34 def method_missing(*argv)
35 call_command(argv)
36 end
37
38 def call_command(argv)
39 bulk = nil
40 argv[0] = argv[0].to_s.downcase
41 if BulkCommands[argv[0]]
42 bulk = argv[-1]
43 argv[-1] = bulk.length
44 end
45 @sock.write(argv.join(" ")+"\r\n")
46 @sock.write(bulk+"\r\n") if bulk
47 read_reply
48 end
49
50 def select(*args)
51 raise "SELECT not allowed, use the :db option when creating the object"
52 end
53
54 def [](key)
55 get(key)
56 end
57
58 def []=(key,value)
59 set(key,value)
60 end
61
62 def read_reply
63 line = @sock.gets
64 case line[0..0]
65 when "-"
66 raise line.strip
67 when "+"
68 line[1..-1].strip
69 when ":"
70 line[1..-1].to_i
71 when "$"
72 bulklen = line[1..-1].to_i
73 return nil if bulklen == -1
74 data = @sock.read(bulklen)
75 @sock.read(2) # CRLF
76 data
77 when "*"
78 objects = line[1..-1].to_i
79 return nil if bulklen == -1
80 res = []
81 objects.times {
82 res << read_reply
83 }
84 res
85 end
86 end
87 end