Home » Ruby » Zache: A Simple Ruby In-Memory Cache

About Yegor Bugayenko

Yegor Bugayenko
Yegor Bugayenko is an Oracle certified Java architect, CEO of Zerocracy, author of Elegant Objects book series about object-oriented programing, lead architect and founder of Cactoos, Takes, Rultor and Jcabi, and a big fan of test automation.

Zache: A Simple Ruby In-Memory Cache

A month ago I stumbled upon a problem: I wasn’t able to find a Ruby gem which would do in-memory caching with the capability to expire on timeout. After some quick research I decided to implement my own and called it Zache (as in “zero cache,” since there is no back end). Here is how it works:

First, you create the cache:

1
2
require 'zache'
zache = Zache.new

 

Then you fetch the value by the key, also providing the block which will be executed if the key is absent or expired:

1
2
3
4
x = zache.get(:x, lifetime: 15) do
  # Something very slow and expensive, which
  # we only want to execute once every 15 seconds.
end

 

Here, :x is the key and 15 is the number of seconds it will stay in the cache, until it expires.

It’s important to notice that the key won’t be deleted from the cache automatically. It will stay there until the next call to get(:x). Only at that moment will it be marked as “expired.” In order to clean up the cache, you can call zache.clean() and all expired keys will be deleted.

You can do it regularly in a separate thread, for example, every minute:

1
2
3
4
Thread.start do
  sleep 60
  zache.clean
end

 

Also, Zache, of course, is thread-safe.

The gem is in this GitHub repository. Feel free to report bugs, if you find them, or help us with additional features.

Published on Web Code Geeks with permission by Yegor Bugayenko, partner at our WCG program. See the original article here: Zache: A Simple Ruby In-Memory Cache

Opinions expressed by Web Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of