Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add :force option to cache! #425

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ Fragment caching is supported, it uses `Rails.cache` and works like caching in
HTML templates:

```ruby
json.cache! ['v1', @person], expires_in: 10.minutes do
json.cache! ['v1', @person], expires_in: 10.minutes, force: true do
json.extract! @person, :name, :age
end
```
Expand Down
2 changes: 2 additions & 0 deletions gemfiles/.bundle/config
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
BUNDLE_RETRY: "1"
3 changes: 2 additions & 1 deletion lib/jbuilder/jbuilder_template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ def _render_partial(options)

def _cache_fragment_for(key, options, &block)
key = _cache_key(key, options)
_read_fragment_cache(key, options) || _write_fragment_cache(key, options, &block)
force = options[:force].present?
(!force && _read_fragment_cache(key, options)) || _write_fragment_cache(key, options, &block)
end

def _read_fragment_cache(key, options = nil)
Expand Down
29 changes: 29 additions & 0 deletions test/jbuilder_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,35 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
assert_equal "Miss", result["b"]
end

test "fragment caching a JSON object with force option" do

render(<<-JBUILDER)
json.cache! "cachekey" do
json.test1 "Value"
end
JBUILDER

result = render(<<-JBUILDER)
json.cache! "cachekey", force: false do
json.test1 "New Value"
end
JBUILDER
assert_equal "Value", result["test1"]

result = render(<<-JBUILDER)
json.cache! "cachekey", force: true do
json.test1 "New Value"
end
JBUILDER
assert_equal "New Value", result["test1"]
result = render(<<-JBUILDER)
json.cache! "cachekey" do
json.test1 "Cache Miss"
end
JBUILDER
assert_equal "New Value", result["test1"]
end

test "object fragment caching with expiry" do
travel_to "2018-05-12 11:29:00 -0400"

Expand Down