user3599334
user3599334

Reputation: 97

How can I use cache_if method from controller, not view?

Inside view, i can write:

= cache_if Rails.env.production?, my_cache_key do
  ...

But how can I use cache_if method from controller, not view?

Upvotes: 0

Views: 438

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176472

cache_if is a view helper. It is designed to be mixed in a view context, not in a controller.

You can't use it in a controller. You could try to mix the helper into the controller, but it was not designed for that hence you should not adopt that approach.

Instead, you can use Rails.cache to access the cache store. You can then write your own implementation, if you want even cloning the cache_if implementation:

def cache_if(condition, name = {}, options = nil, &block)
  if condition
    Rails.cache.fetch(name, options, &block)
  else
    yield
  end
end

Upvotes: 2

Related Questions