Add this line to your Gemfile
and run bundle install
# Gemfile
gem "redis"
Create a new initializer to have a global $redis
variable at hand:
touch config/initializers/redis.rb
# config/initializers/redis.rb
$redis = Redis.new
url = ENV["REDISCLOUD_URL"]
if url
Sidekiq.configure_server do |config|
config.redis = { url: url }
end
Sidekiq.configure_client do |config|
config.redis = { url: url }
end
$redis = Redis.new(:url => url)
end
Then create a new Cache
service:
mkdir -p app/services
touch app/services/cache.rb
Open this cache.rb
file and paste the following code:
class Cache
include Singleton
EXPIRE = 1.week
def get(*args, &block)
the_key = key(*args)
if (value = redis.get(the_key)).nil?
value = yield(self)
redis.set(the_key, Marshal.dump(value))
redis.expire(the_key, expire)
value
else
Marshal.load(value)
end
end
def key(*args)
"cache:#{args.join(":")}"
end
end
Then to use the cache on an API for instance:
require "open-uri"
url = "https://api.github.com/users/ssaunier"
result = Cache.instance.get(:api_user, url) do
JSON.parse(open(url).read)) # Expensive (long) call to cache
end