Skip to content

Instantly share code, notes, and snippets.

@rlogwood
Last active October 20, 2021 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlogwood/97326e9cdae84af1183eecde9023cccc to your computer and use it in GitHub Desktop.
Save rlogwood/97326e9cdae84af1183eecde9023cccc to your computer and use it in GitHub Desktop.
Example Stimulus Page Reloader Controller for Rails 7
<!DOCTYPE html>
<html>
<head>
<title>RefresherDemo</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
</head>
<body>
<!-- to disable auto refresh, remove data-refresher-reload-interval-value -->
<div data-controller="refresher" data-refresher-debug-value="true" data-refresher-reload-interval-value="5000">
<h2>Change Me To Something New</h2>
<%= yield %>
</div>
</body>
</html>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = { reloadInterval: Number, debug: Boolean }
initialize() {
if (this.debugValue) {
console.log(`Refresher Initialized: Debug active (data-refresher-debug-value='${this.debugValue}')`);
} else {
console.log("Refresher Initialized: Debug OFF (data-refresher-debug-value='false')");
}
if (this.hasReloadIntervalValue) {
console.log(`Refresher Initialized: data-refresher-reload-interval-value='${this.reloadIntervalValue}'`)
} else {
console.log("Refresher Initialized: will not refresh, data-refresher-reload-interval-value is NOT defined");
}
}
connect() {
if (this.debugValue) {
console.log("Refresher Connected")
}
if (this.hasReloadIntervalValue) {
this.#startRefreshing()
}
}
disconnect() {
if (this.debugValue) {
console.log("Refresher Disconnected")
}
this.#stopRefreshing()
}
// private methods
#startRefreshing() {
console.log("Refresh Started with",this.reloadIntervalValue/1000.0,"second intervals...")
this.refreshTimer = setInterval(() => {
this.#load()
console.log("Refresher reloaded at", Date().toString())
}, this.reloadIntervalValue)
}
#stopRefreshing() {
if (this.refreshTimer) {
clearInterval(this.refreshTimer)
}
}
#load() {
location.reload()
}
}
@rlogwood
Copy link
Author

@ParamagicDev Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment