Question

I was always wondering exactly how does Rails generate cache and in particular, does:

cache [@users, @products]

Behave like:

cache @users.concat(@products)
Was it helpful?

Solution

The method is:

  # Expands out the +key+ argument into a key that can be used for the
  # cache store. Optionally accepts a namespace, and all keys will be
  # scoped within that namespace.
  #
  # If the +key+ argument provided is an array, or responds to +to_a+, then
  # each of elements in the array will be turned into parameters/keys and
  # concatenated into a single key. For example:
  #
  #   expand_cache_key([:foo, :bar])               # => "foo/bar"
  #   expand_cache_key([:foo, :bar], "namespace")  # => "namespace/foo/bar"
  #
  # The +key+ argument can also respond to +cache_key+ or +to_param+.
  def expand_cache_key(key, namespace = nil)
    expanded_cache_key = namespace ? "#{namespace}/" : ""

    if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
      expanded_cache_key << "#{prefix}/"
    end

    expanded_cache_key << retrieve_cache_key(key)
    expanded_cache_key
  end

Let's define a shortcut:

def cache(*args); ActiveSupport::Cache.expand_cache_key(*args); end

And for readability:

ENV["RAILS_CACHE_ID"] = ''

So it's recursive, for instance:

cache 'string'
=> "/string"

cache [1, 2]
=> "/1/2"

cache [1, 2, 3, 4]
=> "/1/2/3/4"

cache [1, 2], [3, 4]
=> "[3, 4]//1/2"

cache [[1, 2], [3, 4]]
=> "/1/2/3/4"

cache [@users, @products]
=> "/users/207311-20140409135446308087000/users/207312-20140401185427926822000/products/1-20130531221550045078000/products/2-20131109180059828964000/products/1-20130531221550045078000/products/2-20131109180059828964000"

cache @users.concat(@products)
=> "/users/207311-20140409135446308087000/users/207312-20140401185427926822000/products/1-20130531221550045078000/products/2-20131109180059828964000/products/1-20130531221550045078000/products/2-20131109180059828964000"

As you can see, the second parameter is a namespace, so always put your parameters in an array.

So to reply to my question, it's the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top