/
command_helper.rb
45 lines (38 loc) · 1008 Bytes
/
command_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true
class Redis
module Connection
module CommandHelper
COMMAND_DELIMITER = "\r\n"
def build_command(args)
command = [nil]
args.each do |i|
if i.is_a? Array
i.each do |j|
j = j.to_s
j = j.encoding == Encoding::BINARY ? j : j.b
command << "$#{j.bytesize}"
command << j
end
else
i = i.to_s
i = i.encoding == Encoding::BINARY ? i : i.b
command << "$#{i.bytesize}"
command << i
end
end
command[0] = "*#{(command.length - 1) / 2}"
# Trailing delimiter
command << ""
command.join(COMMAND_DELIMITER)
end
protected
def encode(string)
string.force_encoding(Encoding.default_external)
unless string.valid_encoding?
string.force_encoding(Encoding::BINARY)
end
string
end
end
end
end