There is Redis.current
, which you can use to store your one-and-only Redis
instance.
So instead of using $redis
, you can assign your instance as follows:
Redis.current = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])
Redis.current
was introduced to redis-rb in 2010 as a standard way to grab a redis connection, so I was surprised that no other answer mentioned it.
Update: Starting with version 4.6.0 Redis.current
has been deprecated. The author notes that typical multi-threaded applications will find a lot of locking around a shared redis client. They recommend to define an own place to get a redis client, but also suggest to use a connection pool.
The accepted answer is therefore the simplest solution to achieve something comparable to Redis.current
, but may not perform optimal in multi-threaded environments.