Skip to content

Commit 2af83b3

Browse files
committedDec 20, 2024·
Encapsulate stale_when_importmap_changes
1 parent f588506 commit 2af83b3

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed
 

‎README.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -226,14 +226,16 @@ Import your module on the specific page. Note: you'll likely want to use a `cont
226226

227227
## Include a digest of the import map in your ETag
228228

229-
If you're using [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) generated by Rails helpers like `stale?` or `fresh_when`, you need to include the digest of the import map into this calculation. Otherwise your application will return [304](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304) cache responses even when your JavaScript assets have changed. You can avoid this with something like:
229+
If you're using [ETags](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) generated by Rails helpers like `stale?` or `fresh_when`, you need to include the digest of the import map into this calculation. Otherwise your application will return [304](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304) cache responses even when your JavaScript assets have changed. You can avoid this using the `stale_when_importmap_changes` method:
230230

231231
```ruby
232232
class ApplicationController < ActionController::Base
233-
etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
233+
stale_when_importmap_changes
234234
end
235235
```
236236

237+
This will add the digest of the importmap to the etag calculation when the request format is HTML.
238+
237239

238240
## Sweeping the cache in development and test
239241

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module Importmap::Freshness
2+
def stale_when_importmap_changes
3+
etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
4+
end
5+
end

‎lib/importmap/engine.rb

+7
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ class Engine < ::Rails::Engine
4848
end
4949
end
5050

51+
initializer "importmap.concerns" do
52+
ActiveSupport.on_load(:action_controller_base) do
53+
require_relative "../../app/controllers/concerns/importmap/freshness"
54+
extend Importmap::Freshness
55+
end
56+
end
57+
5158
initializer "importmap.helpers" do
5259
ActiveSupport.on_load(:action_controller_base) do
5360
helper Importmap::ImportmapTagsHelper

0 commit comments

Comments
 (0)
Please sign in to comment.