Skip to content

Commit 2ef81f0

Browse files
authored
Encapsulate stale_when_importmap_changes method (#284)
* Encapsulate stale_when_importmap_changes * Use autoload instead of relative require
1 parent f588506 commit 2ef81f0

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
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

+5
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-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class Engine < ::Rails::Engine
1111
config.importmap.cache_sweepers = []
1212
config.importmap.rescuable_asset_errors = []
1313

14-
config.autoload_once_paths = %W( #{root}/app/helpers )
14+
config.autoload_once_paths = %W( #{root}/app/helpers #{root}/app/controllers )
1515

1616
initializer "importmap" do |app|
1717
app.importmap = Importmap::Map.new
@@ -48,6 +48,12 @@ class Engine < ::Rails::Engine
4848
end
4949
end
5050

51+
initializer "importmap.concerns" do
52+
ActiveSupport.on_load(:action_controller_base) do
53+
extend Importmap::Freshness
54+
end
55+
end
56+
5157
initializer "importmap.helpers" do
5258
ActiveSupport.on_load(:action_controller_base) do
5359
helper Importmap::ImportmapTagsHelper

0 commit comments

Comments
 (0)