Awesome
Rails Cache Tags
Tagged caching support within your Rails application. Tested against Rails 3.x and Rails 4.0. Dalli store is also supported!
Installation
Add this line to your application's Gemfile:
gem 'rails-cache-tags'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rails-cache-tags
Usage
Anywhere:
cache = Rails.cache
cache.write "foo", "bar", :tags => %w(baz foo)
cache.read "foo" # => "bar"
cache.delete_tag "baz"
cache.read "foo" => nil
More realistic example:
class PostsController < ApplicationController
def index
@posts = cache.read("posts") || begin
posts_from_db = Post.all
cache.write "posts", posts_from_db, :tags => {:post => posts_from_db.map(&:id)}
posts_from_db
end
end
def show
id = params[:id]
@post = cache.fetch(["post", id], :tags => {:post => id}) do
Post.find(id)
end
end
def update
@post = Post.find(params[:id])
if @post.update_attributes
cache.delete_tag :post => @post.id
end
end
end
In your controller:
class PostController < ActionController::Base
def update
@post = Post.find_by_id(params[:id])
if @post.update_attributes(params)
expire_fragments_by_tags :post => @post.id
else
render :edit
end
end
end
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Write tests!
- Run tests against all major version of Rails starting from 3.0
- Push to the branch (
git push origin my-new-feature
) - Create new Pull Request