Let us learn how we can connect Redis with Ruby application.
Basic knowledge in working with Redis and Ruby.
Install Ruby interpreter and Redis server on your system.
Installing Redis Ruby Client
To connect Ruby with Redis, we need to install a Redis Ruby client. For this article, we will use redis-rb gem.
Open the terminal and enter the command below to install:
Once installed, we can proceed to connect redis with our app.
Connecting Ruby to Redis
Create a working directory and add the file to hold your code.
Open the file and add the code as shown below:
# connect with default
redis = Redis.new
# connect with password ro database 0
redis = Redis.new(url: "redis://:[email protected]:6379/0")
In the code above, we start to import the required modules.
Next, we connect to Redis using the new method. If your Redis server is secured with a password, opt for connection method 2.
Testing Redis Connection
To test the connection, you can run redis.ping method as shown:
This should return PONG upon successful connection.
Setting Ruby Key-Value pair
Create a new key-value pair to the database by using the set command as:
This should return like this:
Getting Ruby Value
To get a value associated with a key in Redis, use the get method as shown:
This should return the value associated with the key:
Setting Ruby Expiring Key
To create a key-value pair with expiry duration, use the setex method as:
The above should create a key with an expiry duration of 60 seconds.
In this article, you learn how to connect your Redis database to a Ruby application through a comprehensible walk-through of the whole process. Check the docs to learn more.