rails-api/active_model_serializers — pull request #343 by tjschuck (2013-06-27 19:42:53+00:00)
Title: Respect global caching configuration

This pull request fixes a bug with the caching feature (that's really only documented in its [initial pull request](https://github.com/rails-api/active_model_serializers/pull/89)).

According to the [docs for ActionController::Caching](http://api.rubyonrails.org/classes/ActionController/Caching.html):

> Note: To turn off all caching, set
>
> config.action_controller.perform_caching = false

Currently, the caching feature does not respect this setting, and additionally overrides it leading to some odd behavior.

### Issue in Dev and Test Environments

Default `config/environments/development.rb` and `config/environments/test.rb` both have:

config.action_controller.perform_caching = false

This makes sense. However, with this serializer:

```ruby
class PostSerializer < ActiveModel::Serializer
cached

attributes :id, :title, :body

def cache_key
object.cache_key
end
end
```

_Caching occurs in dev and test._ It shouldn't.

### Issue in Production Environments

Default `config/environments/production.rb`:

config.action_controller.perform_caching = true

With _this_ serializer:

```ruby
class PostSerializer < ActiveModel::Serializer
# cached

attributes :id, :title, :body

def cache_key
object.cache_key
end
end
```

_i.e._, caching explicitly turned **OFF** (but with a left-behind `cache_key` definition), it _gets cached in production_. It shouldn't.

### The Fix

The original implementation conflated the global configuration to enable caching with the per-serializer enabling of caching. This pull request bubbles the configuration concepts (whether caching is globally enabled (`perform_caching`), and whether a cache store is present (`cache_store`)) up to the `Caching` module, and adds a new per-serializer cache-enabling attribute to the `Serializer` and `ArraySerializer` classes (`cache_enabled`) to keep them independent of the `perform_caching` config value.

Tests have been added as well.

#### A brief aside on naming:

* `cache` was renamed to `cache_store` to decrease ambiguity. The former is mighty generic, and can be read as a verb or a noun. The latter is much more clearly a noun/object. This also jibes better with the language used within the Rails codebase.

* `perform_caching` and `cache_enabled` are the closest I could get to accurately describing what they do. To be _more_ accurate, they should probably be flip-flopped for what each indicates, but `perform_caching` comes from Rails config itself, so we should probably stick with the same language.