This is a simple Ruby on Rails app showing how a service worker can be used to cache pages and display them offline using Google Workbox.
It has a default offline fallback for pages that are not found in the cache but are registered with the service worker. This applies to pages that are registered with a NetworkOnly or a NetworkFirst strategy (for this latter strategy either the page was never cached or the cache expired or was deleted).
The service worker caching is covered by system tests. This is made possible by setting network conditions for both the browser and the service worker.
View the deployed offline demo app (may take a little time to spin up).
To avoid hard coded static paths in the service worker, routes are annotated using the defaults: option by setting sw_offline_cache:, sw_warm_cache: or sw_no_fallback: to true.
Pages that are warm cached are cached as soon as the service worker is installed so even if a user never accesses a page they will be able to view it offline.
To run all the tests run the following command from the terminal:
bin/rspec -t run_first && bin/rspecBy default the tests run headless but to see them run in a browser, prefix both calls to bin/rspec with HEADLESS=false. By default running just bin/rspec excludes tests tagged with run_first.
The selenium-webdriver gem is being used to run system tests since cuprite chrome driver does not support service workers yet but this could change.
System tests should only run once the service worker has activated. To enforce this the service worker state is checked in a before hook and only when the state is activated do tests run.
To cache dynamic paths and paths with query parameters (eg pagination) you can use regular expressions or check what a path starts with in the service_worker.js.erb file.
Service workers are complicated so please use this demo just for ideas. A real life example of a sophisticated offline capable Rails app is the Rails World Conference App.