Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,20 @@ 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
end
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
Expand Down
1 change: 1 addition & 0 deletions grape-rails-cache.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
9 changes: 8 additions & 1 deletion lib/grape/rails/cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand All @@ -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
Expand Down