It’s a bit difficult as an old-timer to figure out where/how to put basic javascript in a rails 8 project, because it seems the documentation either doesn’t exist yet, or is tailored for older versions of rails. As someone who hasn’t kept up with anything in the last decade, here’s how I did it. Would love some feedback.
What I’m trying to do is wrap up a little bit of code to generate some charts on a html page, and I am not trying to wrap it into a SPA or stimulus controller or anything complex. I’m a big fan of bare minimum js. This stuff was previously just inline in <script>
tags in my html page, for reference.
- Create a file:
app/javascript/saved_graph.js
- generating a simple class and exporting it. Loosely creating a class-like object and doing the work of processing data and making a chart.
let SavedGraph = {
id: 0,
init: function(id) {
console.log("Initializing SavedGraph...");
SavedGraph.id = id;
},
prepareData: function(data) { .... },
renderChart: function() { ...}
}
export { SavedGraph }
- Now, in app/javascript/application.js: modifying the boilerplate and importing the class to the window scope.
// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import { SavedGraph } from './saved_graph.js';
// things imported here aren't available to the html page, so ..
window.SavedGraph = SavedGraph;
- In my actual html.erb file, attach to the window onload event to wait for the class to be loaded and Do Stuff on my page.
<% content_for :head do %>
window.addEventListener('load', function() {
window.SavedGraph.init(<%= @saved_graph.id %>);
window.SavedGraph.prepareData(....);
);
<% end %>
So while this works, is there a more idiomatic way of doing all this? Or something with event less boilerplate or magic incantations? How little code can I get away with?