A simple framework-agnostic cache with Redis.
Add this line to your application's Gemfile:
gem 'rb-redis-cache'
And then execute:
bundle install
Or install it yourself as:
gem install rb-redis-cache
You can connect to Redis by configuring the RedisCache::Store
class:
require 'redis_cache'
cache = RedisCache::Store.new(url: REDIS_URL)
Alternatively, you can pass options to the Store
instance:
require 'redis_cache'
cache = RedisCache::Store.new(url: REDIS_URL, connect_timeout: 10)
Defaults are defined in lib/redis_cache.rb and can be overrided.
You can store data structures that can be serialized to JSON.
cache.write('my_key', 'my_value')
my_hash = {a: 'a', b: 'b', c: [{ d: 'd' }]}
cache.write('my_key', my_hash)
Optionaly, you can set an expiry time in seconds fot the key.
cache.write('my_key', 'my_value', expires_in: 60)
cache.read('my_key')
=> 'my_value'
Increments the number stored at key by increment.
cache.increment('my_key_inc')
=> 1
cache.increment('my_key_inc')
=> 2
Decrements the number stored at key by decrement.
cache.increment('my_key_inc')
=> 1
cache.increment('my_key_inc')
=> 2
cache.decrement('my_key_inc')
=> 1
cache.write('my_key', 'my_value')
cache.exist?('my_key')
=> true
cache.exist?('my_other_key')
=> false
cache.delete('my_key')
You can fetch a key from the cache, if there is an existing value for a given key, then this value is returned. If there is no value for the given key, and a block parameter has been passed, then the result will be cached and returned.
cache.fetch('my_key', expires_in: 60) do
block_method_calculation
end
=> 'my_value'
After checking out the repo, run bin/setup
to install dependencies. Then, run rake test
to run the tests. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/jveillet/rb-redis-cache/issues.
The gem is available as open source under the terms of the MIT License.