StimulusReflex: Reflexes, data-reflex & Morphing
StimulusReflex builds on Stimulus's lightweight controller pattern, letting client-side actions trigger server-side Ruby "Reflex" methods over a WebSocket connection (Rails' Action Cable) -- re-rendering parts of the page without a full reload or a separate JSON API.
Triggering a Reflex
<button data-reflex="click->Counter#increment">+1</button>
<%# StimulusReflex's client library intercepts the click,
sends it over the WebSocket, and applies the re-rendered
HTML back to the page automatically %>Defining a Reflex
class CounterReflex < StimulusReflex::Reflex
def increment
@count = (session[:count] || 0) + 1
session[:count] = @count
end
end
# @count is available to the re-rendered view, just like
# an instance variable set in a normal Rails controller actionWhat Happens After a Reflex Runs
The relevant view is re-rendered server-side, and the resulting HTML is morphed into the existing DOM -- an SPA-like update with no full page reload and no hand-written DOM manipulation code.
CableReady: Granular DOM Control
CableReady provides a Ruby API for targeted DOM operations (morphing a specific element, dispatching a custom event) from server code -- finer control than the default whole-section re-render, and useful for scoping updates narrowly to avoid disrupting unrelated UI state like scroll position.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free