While IronCache is a great option for caching, it can also be used to persist data more permanently. There are dozens of great uses for a persistent key/value store, however, we’ll be building a simple chat app with Sinatra using IronCache as our datastore.
First let’s talk about a traditional cache. Take Memcached for example, it’s an in memory, non-durable, key/value store. It’s great! It’s probably the most popular object caching system there is. Until now, Memcached has always been my go-to solution.
Initially I built my mini-chat app Chattyloo using Postgres. Postgres is a big hammer,
for quite a simple problem. I know I needed persistence and durability, but I didn’t need such a serious Object Relationship Mapper. Moreover I didn’t want to manage a database, and that was the biggest factor to move over to IronCache.
Now there is one relationship here, but it’s actually an advantage in the case of a chat app. I needed to have one relationship, as chat rooms have chats. The way around this is to store all your chats as a single value for that room. I’ve created an ORM-like finder:
Now this is a sinatra app so
settings is a hash, and
ironcache is just an instance of
IronCache::Client, see here: https://github.com/jpsilvashy/chattyloo/blob/master/app.rb#L22
When a new chat is POST’ed, we insert it like so:
last(), trims off the messages so we don’t grow the size of the object too large, as they are all loaded at once.
Lastly, chats are retrieved like so:
This finder will return the channel with the messages. Now in your views you can iterate over the
@messages for a given instance of