In our last post, we persisted and restored a collapsed/expanded UI state with Kredis. However, the great pain point with this is that we have to invent a lot of Kredis keys.
This time, we'll see how we can avoid this by developing a generalized solution for any DOM node whose attribute states we want to track on the server side.
Let's dive straight in!
The Challenge
Remember that we had to concoct a Kredis set key (open_department_ids
) on the user model in the previous post. Now, following our example, imagine a user might be associated to the products they bought via has_many
. Assume that each of these products has a details page which also has some ephemeral state attached.
All of a sudden, the complexity increases tremendously: we now have N kredis_sets
to cater for, prefixed with the product ID. Or we could handle it on the Product
model, storing the state for each user ID. Either way, it is going to get cumbersome, and we'll likely have to resort to metaprogramming to smooth it out a bit.
This, you'll agree with me, is not a delightful challenge. It would be very beneficial for the app's architecture if we could abstract that away.
And this is precisely what we are going to attempt. We'll use an accordion on the product details page to illustrate this case and also its resolution.
Preparation
To start, we'll add two more text columns, description
and specs
, to our Product
model:
Again, in the Rails console, we'll provide some seed data:
Finally, let's amend the _product
partial to include those two new properties in an "accordion", again making use of the <details>
element.
In our home index view, let's link to the products:
Here's the detail of the view this produces:
Observing UI Changes with JavaScript
Now we have to rewrite our UIState
Stimulus controllers to listen for arbitrary DOM changes. We do this by placing a MutationObserver
on its element, which looks for attribute changes after it connects. In its callback (mutateState
), the following happens:
- All attributes on the element, except for the
data-controller
attribute itself, are collected. - Their respective values are stored on an
attributes
object with theirname
as the key. - This object is appended to a new
FormData
object, along with a uniquekey
that identifies the exact instance of the UI state (we'll get to that in a moment). - This is then sent over to the server as before, in the form of a
PATCH
request.
Persisting UI State with Unique Kredis Keys
To generalize persisting UI state, we have to accomplish two things:
- Generate unique Kredis keys regarding the user, resource (in our case, the product), and the location in the view, respectively.
- Use these keys to persist the attributes object received from the client.
Using Rails Helpers
So first, we have to solve the problem of coming up with unique keys. If you look at the requirements carefully, they read a lot like the built-in Rails fragment cache
helper.
In short, this helper will build a cache key based on the template it's called from, and any cacheable Ruby objects passed to it. To quote the documentation:
We don't need the cache
helper though, because we are not actually storing a fragment, we just need a key. Thankfully, the method it calls internally to generate one, cache_fragment_name
, is also exposed.
Let's check out how we can make use of this. If we add the following line to our products/_product.html.erb
partial:
Something like this is rendered:
Clearly, this nested array needs some massaging, but we are already very close. What's still missing is a reference to the specific line in the template, but we can obtain this from the call stack's first entry representing a template. Let's extract this to a helper and convert it to a string:
Note: We are skipping the view digesting as including the caller location makes it redundant.
Called as ui_state_key([current_user, product])
, this yields a string of the following format:
Now there's one final piece to solve: because we will include this key in our markup (to be picked up by the Stimulus controller above), we'll want to obfuscate it. Otherwise, it would be easy for a bad actor to exchange the user ID and/or the product global ID using the browser's developer tools. A simple digest will do in our case, because we do not intend to decrypt it back.
That's it, now we can obtain a digest of our UI fragment that will be unique to the location in the template and its MTIME, as well as user and resource:
Attach Stimulus Controllers to Your Rails App
Equipped with this, we can now attach the Stimulus controllers along with the respective keys to our <details>
elements:
We can now set out to generalize the UIStateController
as well. For this, we obtain a new Kredis.json
key using the transmitted key
param. Whenever a UI state update
occurs, all the attributes
sent over as form data will be parsed and stored therein.
Rehydrating the UI
Since our UI state is now safely stored in an ephemeral Kredis key, the only piece of the puzzle that's missing is how to put the UI back together. This process is called rehydration. In this example, we'll use server-side rehydration.
For this, we will revisit the ui_state_key
helper from above, and extend it with the rehydration logic.
The remember_ui_state_for
helper takes a name
argument that it will pass on to the ui_state_key
helper from above. Before it does that, though, it will capture
the HTML from the block passed to it and extract its first fragment child with Nokogiri.
Afterward, the actual rehydration logic starts:
- the
ui_state
is read back fromKredis
- in case such a key already exists, each
attribute
is put back on the HTML element obtained in the previous step. To prevent any XSS vulnerabilities, the attributes' values are alsosanitized
- finally, the Stimulus controller is attached to the element, along with the
ui_state_key
.
Any change to the attributes would now again be transmitted by the MutationObserver
, and any page reload would invoke this helper again, rehydrating them upon the element.
Note: An additional security mechanism would be safelisting the allowed attributes, which I have excluded from this example for simplicity.
In our product partial, instead of wiring up the Stimulus controller manually, we must now use the new view helper:
This is what the end result looks like:
It turns out that this approach is perfect for HTML elements or custom web components that reflect their state in one or more attributes (e.g. <details>
, Shoelace, Lit, etc.).
Wrapping Up
In part one of this series, we described what Kredis can and cannot do, and developed an example use case for storing ephemeral UI state using a bespoke Redis key.
In this second and final part, we identified the drawbacks of this approach. We developed a generalized solution to apply to any DOM node whose state of attributes we want to track on the server side.
Finally, let me point out that these considerations inspired me to develop a library called solder, which I would be happy to receive feedback on!
Happy coding!
P.S. If you'd like to read Ruby Magic posts as soon as they get off the press, subscribe to our Ruby Magic newsletter and never miss a single post!