Using Alternate Session Stores with Sinatra
To turn on sessions normally, you just have to run:
enable :sessions
# OR
set :sessions, true
Under the covers, that sets up Rack::Session::Cookie as a rack middleware component. If you were to do this manually, it would look like:
use Rack::Session::Cookie
The problem with relying on this is that the Cookie session store limits you to storing only 4k of data. It’s normally not a great idea to store a ton of data in the session, but it’s sometimes necessary. The other problem with using the cookie session stores is that the data is stored unencrypteted (but packed as base64). So you open your application up to a potential attack from a malicious user manipulated cookie.
So what we need to do in order to “use” the alternate session implementation is just to run:
use Rack::Session::Pool
# Or another session store that matches the rack API
# DON'T enable :session
# DON'T set :session, true
I haven’t seen many session implementations in Rack, but the edge Rack (and the next release presumably) will make it simple to create new implementations. Just check out Rack::Session::Abstract::Id for some helpers. Also, edge Rack does support a Memcached session adapter, which looks pretty promising as a usable session container.
August 18th, 2008 at 12:26 am
Thanks to good posting. It’s very helpful for sinatra newbie like me.
However, just one thing made me confuse. Above way that you described is working well only on sinatra edgy(0.2.3). On gem version(0.2.2), it’s not work. So, at first, I don’t know why my example was not work (I used sinatra gem version :-)).
Anyway, thanks a lot. :-)