Lightly - Ruby File Cache

Gem Travis Code Climate Gemnasium


Lightly is a file cache for performing heavy tasks, lightly.


Install

$ gem install lightly

Or with bundler:

gem 'lightly'

Usage

require 'lightly'

lightly = Lightly.new

content = lightly.with 'key' do
  # Heavy operation here
end

This will look for a cached object with the given key and return it if it exists and not older than 1 hour. Otherwise, it will perform the operation inside the block, and save it to the cache object.

By default, the cached objects are stored in the ./cache directory, and expire after 60 minutes. The cache directory will be created as needed.

In addition, the provided key is hashed to its MD5 representation.

You can change these settings on initialization:

lightly = Lightly.new dir: 'tmp/my_cache', life: 7200, hash: false

Or later:

lightly = Lightly.new
lightly.dir = 'tmp/my_cache'
lightly.life = 7200 # seconds
lightly.hash = false

To check if a key is cached, use the cached? method:

lightly = Lightly.new
lightly.cached? 'example'
# => false

content = lightly.with 'example' do
  open('http://example.com').read
end
lightly.cached? 'example'
# => true

You can enable/disable the cache at any time:

lightly = Lightly.new
lightly.disable
lightly.enabled? 
# => false

content = lightly.with 'example' do
  open('http://example.com').read
end
lightly.cached? 'example'
# => false

lightly.enable
content = lightly.with 'example' do
  open('http://example.com').read
end
lightly.cached? 'example'
# => true

To flush the cache, call:

lightly = Lightly.new
lightly.flush

The key method is an alias to with, if you prefer a different wording:

cache = Lightly.new

content = cache.key 'example' do
  # Heavy operation here
end

For a similar gem that provides caching specifically for HTTP downloads, see the WebCache gem