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.
Written by Tymon Tobolski
Related protips
1 Response
+1
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#