fpww3q
Last Updated: February 25, 2016
·
4.269K
· teamon
9fae8c5d475fe322a3a74e53d56ee2a0

Render cached json using rails and redis

Requirements

  • rails
  • redis-rails
class MyController
  def index
    render_cached_json("api:foos", expires_in: 1.hour) do
      Foo.all
    end
  end

  def render_cached_json(cache_key, opts = {}, &block)
    opts[:expires_in] ||= 1.day

    expires_in opts[:expires_in], :public => true
    data = Rails.cache.fetch(cache_key, {raw: true}.merge(opts)) do
      block.call.to_json
    end

    render :json => data
  end
end

This will store rendered json in redis, plain json, as string, as you should it should always do. Notice where is to_json and raw: true option. And you get HTTP cache headers for free

Why?

Because respond_with sucks and storing marshaled ActiveSupport::Cache::Entry object in redis is just damn stupid.

Say Thanks
Respond

1 Response
Add your response

7607
6c6088d4a7d9d07e28a13d9c2677d5a6

+1

over 1 year ago ·