diff --git a/README.md b/README.md index 35f15f6..91cb47b 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ module MyApi < Grape::API desc "Return a post" get ":id" do post = Post.find(params[:id]) - cache(key: "api:posts:#{post.id}", etag: post.updated_at, expires_in: 2.hours) do + cache(key: "api:posts:#{post.id}", etag: post.updated_at, expires_in: 2.hours, if: -> { !params[:onair] }) do post # post.extend(PostRepresenter) etc, any code that renders response end end @@ -40,6 +40,12 @@ module MyApi < Grape::API end ``` +You can use blocks and symbols as values for `cache` params they will be evaluated in context of `Grape::Endpoint` (see [Uber gem](https://github.com/apotonick/uber#dynamic-options)) + +```ruby +cache(key: -> { "#{request.path}?#{declared_params.except(:client_d).to_json}" } +``` + ## Contributing 1. Fork it diff --git a/grape-rails-cache.gemspec b/grape-rails-cache.gemspec index 975223b..015fdc9 100644 --- a/grape-rails-cache.gemspec +++ b/grape-rails-cache.gemspec @@ -20,6 +20,7 @@ Gem::Specification.new do |spec| spec.add_dependency "grape" spec.add_dependency "activesupport" + spec.add_dependency "uber", "~> 0.0.15" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" diff --git a/lib/grape/rails/cache.rb b/lib/grape/rails/cache.rb index 56ba6e8..fdb7158 100644 --- a/lib/grape/rails/cache.rb +++ b/lib/grape/rails/cache.rb @@ -42,6 +42,8 @@ def default_expire_time end def cache(opts = {}, &block) + opts = Uber::Options.new(opts.reverse_merge(if: true)).evaluate(self) + # HTTP Cache cache_key = opts[:key] @@ -55,7 +57,12 @@ def cache(opts = {}, &block) # Try to fetch from server side cache cache_store_expire_time = opts[:cache_store_expires_in] || opts[:expires_in] || default_expire_time - ::Rails.cache.fetch(cache_key, raw: true, expires_in: cache_store_expire_time) do + + if opts[:if] && cache_store_expire_time > 0 + ::Rails.cache.fetch(cache_key, raw: true, expires_in: cache_store_expire_time) do + block.call.to_json + end + else block.call.to_json end end