A mixin that provides better encapsulation and control when using cache in Rails
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.gitignore
MIT-LICENSE
README.textile
Rakefile
VERSION

README.textile

cache_proxy

A mixin that provides better encapsulation and control when using cache in Rails

Does cache_proxy helps your daily work with Rails? So, please recommend me and Nando Vieira on Working With Rails. Thanks for your kindness! :)

Why?

Using the default Rails abstration for caching will scatter calls to Rails.cache all over your code. Also, it isn’t trivial to bypass the cache when you need to – most of the time you end up creating two versions of the “same” method: one cached and one uncached. Using cache_proxy you will encapsulate the access to the cache and will be able to bypass the cached result using a hash option.

How?

First, install the gem:

$ [sudo] gem install cache_proxy

Then, add it as a dependency in your code using your favorite way (a simple require or mechanisms like the Bundler gem).

The gem will provide you a module to mixin into the classes the access the cache. For example:

class User < ActiveRecord::Base
  include CacheProxy

  has_many :search_terms, :dependent => :destroy, :order => "term ASC"

  def saved_search_terms
    cache_proxy("my_cache_key") do
      self.search_terms
    end
  end
end

The cache_proxy method gives you the possibility of passing in two options:

	# this will bypass the cache and hit the storage, default is true
    cache_proxy("my_cache_key", :cached => false) do
      self.search_terms
    end

	# time to live, default is 30.days
    cache_proxy("my_other_cache_key", :cache_expires_in => 2.hours) do
      self.expensive_canculations
    end

And… that’s it! You can use it both in class and instance methods.

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don’t break it in a
    future version unintentionally.
  • Commit, do not mess with rakefile, version, or history.
    (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Contributors

This library was implemented in conjunction with Nando Vieira, a really great programmer and friend.

License

cache_proxy is released under the MIT license. See MIT LICENSE.