Skip to content

Commit

Permalink
Encapsulate stale_when_importmap_changes
Browse files Browse the repository at this point in the history
  • Loading branch information
dhh committed Dec 20, 2024
1 parent f588506 commit 2af83b3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,14 +226,16 @@ Import your module on the specific page. Note: you'll likely want to use a `cont

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

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:
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:

```ruby
class ApplicationController < ActionController::Base
etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
stale_when_importmap_changes
end
```

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


## Sweeping the cache in development and test

Expand Down
5 changes: 5 additions & 0 deletions app/controllers/concerns/importmap/freshness.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module Importmap::Freshness
def stale_when_importmap_changes
etag { Rails.application.importmap.digest(resolver: helpers) if request.format&.html? }
end
end
7 changes: 7 additions & 0 deletions lib/importmap/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ class Engine < ::Rails::Engine
end
end

initializer "importmap.concerns" do
ActiveSupport.on_load(:action_controller_base) do
require_relative "../../app/controllers/concerns/importmap/freshness"
extend Importmap::Freshness
end
end

initializer "importmap.helpers" do
ActiveSupport.on_load(:action_controller_base) do
helper Importmap::ImportmapTagsHelper
Expand Down

0 comments on commit 2af83b3

Please sign in to comment.