class Redic::Client

Constants

EMPTY
SLASH

Attributes

timeout[RW]

Public Class Methods

new(url, timeout) click to toggle source
# File lib/redic/client.rb, line 12
def initialize(url, timeout)
  @semaphore = Mutex.new
  @connection = false

  configure(url, timeout)
end

Public Instance Methods

configure(url, timeout) click to toggle source
# File lib/redic/client.rb, line 19
def configure(url, timeout)
  disconnect!

  @uri = URI.parse(url)
  @timeout = timeout
end
connect() { || ... } click to toggle source
# File lib/redic/client.rb, line 47
def connect
  establish_connection unless connected?

  @semaphore.synchronize do
    yield
  end
rescue Errno::ECONNRESET
  @connection = false
  retry
end
connected?() click to toggle source
# File lib/redic/client.rb, line 58
def connected?
  @connection && @connection.connected?
end
disconnect!() click to toggle source
# File lib/redic/client.rb, line 62
def disconnect!
  if connected?
    @connection.disconnect!
    @connection = false
  end
end
quit() click to toggle source
# File lib/redic/client.rb, line 69
def quit
  if connected?
    assert_ok(call("QUIT"))
    disconnect!

    true
  else
    false
  end
end
read() click to toggle source
# File lib/redic/client.rb, line 26
def read
  #@connection.read
  @response
end
write(command) click to toggle source
# File lib/redic/client.rb, line 31
def write(command)
  #@connection.write(command)
  cmd_name = command.shift.to_s.downcase
  block = command.find{ |cmd| cmd.is_a? Proc }
  #binding.pry if cmd_name == "subscribe"
  @response = if command.empty?
    @connection.send(cmd_name)
  else
    @connection.send(cmd_name, *command, &block)
  end
rescue => e
  return raise e if e.message =~ /ERR invalid DB index/
  return raise e if e.message =~  /ERR invalid password/
  @response = RuntimeError.new(e.message)
end

Private Instance Methods

assert(value, error) click to toggle source
# File lib/redic/client.rb, line 108
def assert(value, error)
  raise error unless value
end
assert_ok(reply) click to toggle source
# File lib/redic/client.rb, line 112
def assert_ok(reply)
  assert(reply == "OK", reply)
end
call(*args) click to toggle source
# File lib/redic/client.rb, line 101
def call(*args)
  @semaphore.synchronize do
    write(args)
    read
  end
end
establish_connection() click to toggle source
# File lib/redic/client.rb, line 81
def establish_connection
  begin
    #Redic::Connection.new(@uri, @timeout)
    @connection = Redis.new(url: @uri)
    raise StandardError if @connection.ping != "PONG"
  rescue StandardError => err
    raise err, "Can't connect to: #{@uri} because: #{err.message}"
  end

  if @uri.scheme != "unix"
    if @uri.password
      assert_ok(call("AUTH", @uri.password))
    end

    if @uri.path != EMPTY && @uri.path != SLASH
      assert_ok(call("SELECT", @uri.path[1..-1]))
    end
  end
end