Skip to content

Instantly share code, notes, and snippets.

@rkjha
Last active June 8, 2020 10:31
Show Gist options
  • Save rkjha/1e456a2573d25ba150501b576578630a to your computer and use it in GitHub Desktop.
Save rkjha/1e456a2573d25ba150501b576578630a to your computer and use it in GitHub Desktop.
Simple use of Dalli gem to implement caching using memcached in a Sinatra Application.
require 'rubygems'
require 'sinatra/base'
require 'sinatra/content_for'
require 'dalli'
class MyBlog < Sinatra::Base
helpers Sinatra::ContentFor
set :dc, Dalli::Client.new('localhost:11211')
get '/articles/:id' do
# ..............
post_id = params[:id]
key = "post_#{post_id}"
@article = settings.dc.get(key) || set_cache(key, Article.find(post_id))
# ..............
end
def set_cache key, value
settings.dc.set(key, value)
return value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment