user2070369
user2070369

Reputation: 4128

How can I store Session values in Sinatra using Redis?

I'm trying to set up a cluster with Sinatra and Redis, and I need to store session values on redis for this to work, but I can't find the documentation.

Anyone knows how?

Thank you.

Upvotes: 0

Views: 1188

Answers (3)

sashaegorov
sashaegorov

Reputation: 1862

Here is more detailed answer. I think that is very simple to use Sinatra and Redis.

Add Redis gem to application. If you are using Gemfile just add it there.

gem 'redis'

Next you should manage Redis URL in your application:

ENV['REDIS_URL'] ||= 'redis://localhost:6379'
# Redis configuration
RedisURI = URI.parse(ENV["REDIS_URL"])

Here if REDIS_URL isn't set up application will use localhost. For production deployments you should set it to actual production Redis server.

Next is to parse it:

REDIS = Redis.new(host: RedisURI.host, port: RedisURI.port, password: RedisURI.password)

The REDIS constant is Redis connection you may work with.

REDIS.set(param, value) # Set some param to value
REDIS.get(:description) # get description key

In your case you should use unique key for each client. You can handle cookies of client via Sinatra's methods:

response.set_cookie(:foo, 'bar')
request.cookies[:foo]
response.delete_cookie(:foo)

Play with this code and it will be very clear...

You also may implement session expire in Redis.

Upvotes: 1

Sinatra
Sinatra

Reputation: 878

You just need to enable sessions in Sinatra, and save whatever values you need from that session object to redis using the set function.

enable :sessions
redis.set("session_value", session[:value])

Upvotes: 2

ShaneQful
ShaneQful

Reputation: 2236

There is a session object you can access e.g.

get "/bar" do
  session["hello"] = hello
end

Upvotes: 1

Related Questions