简体   繁体   中英

Caching in Ruby Gem, possibly not using Rails

I am rewriting an existing Ruby Gem to include caching. This is for a gem that is relatively commonly used, and accesses a large amount of static data on a web service. Currently, I have a small number of gem users doing a large number of accesses to the service that under normal conditions would be swamping / downing the service , and we're going to put the gem up on github for general consumption.

Right now, users can choose between using the rails cache mechanism, a simple disk cache, or no cache.

What is best practice for letting people choose what cache to use like this (being able to use this outside of rails is a priority so i can't just bail to the underlying caching mechanism)? I'm looking for suggestions/examples for configuration and interface, especially.

Thanks for your suggestions

I wrote a gem called "cachecataz" that has lets any embedder define the caching mechanism/provider they want to use. You can easily use the same methodology to allow the users to pick between multiple different caching mechanisms.

I chose to define the api as a "Provider" and then an "api" which defines which methods are required for any provider. This is what the "Rails.cache" provider and api look like.

Cachecataz.provider = Rails.cache
Cachecataz.api = {:get => :read, :set => :write, :incr => :increment, :exist? => :exist?}

This is a really simple way to have someone choose the Object that responds to the needed methods by the gem writer. Each value in the api hash can either be a symbol or an Object that responds to :call (like Proc or lambda). Then I just use my internal representation in my gem (:get, :set, :incr, :exist?) and lookup the Object/method that needs to be called to execute it at runtime:

def make_api_call(method, *args)
  if Cachecataz.api[method].respond_to?(:call)
    Cachecataz.api[method].call(*args)
  else
    Cachecataz.provider.send(Cachecataz.api[method], *args)
  end
end

This is not all the code, but it is close enough to illustrate how quickly you can implement a pluggable caching api in your own gem and support many cache mechanisms/providers. Cachecataz is open source and up on github if you want to look through the code, it is pretty short and documented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM