Actionview::Component::Live

This is a small add-on to ActionView::Component to make your components update automatically when data is changed serverside.

Usage

Lets say you have a MiniBasketComponent that is renders the small basket in the top of your webshop. Wouldn't it be nice if that just updated it self whenever a change happens to the draft order?

First lets create a small component for our mini basket. This component requires a DraftOrder and will listen to any change to the draft order it renders.

class MiniBasketComponent < ActionView::Component::Base
  include ActionView::Component::Live::Subscriber

  listen_to :draft_order

  def initialize(draft_order:)
    @order = draft_order
  end

  def count
    @order.product_count
  end

  def id
    @order.id
  end
end

Important! There is a strict naming requirement on the listen_to part and named argument in initialize!

Then the component view. The view that should be auto updated must be wrapped in a element that attaches to a Stimulus controller called LiveController. It needs the name of the component and the id of the object that it is attached to.

<div data-controller="live" data-live-component="MiniBasketComponent" data-live-id="<%= id %>">
  <b><%= count %> products in basket</b>
</div>

Finally we need to tell our DraftOrder to broadcast changes.

class DraftOrder < ApplicationRecord
  include ActionView::Component::Live::Broadcaster
end

Thats it. Now any update your draft order will be broadcast through ActionCable and your view will update in real time.

Installation

Add this line to your application's Gemfile:

gem 'actionview-component-live'

And then execute:

$ bundle

Add stimulus controller

$ yarn add stimulus-actionview-live

Add these 2 lines to your app/javascript/controllers/index.js

import LiveController from "stimulus-actionview-live"
application.register("live", LiveController)

Test

Running the tests requires a Redis server to have ActionCable running in a productionlike environment. This might seem like a bit overkill but this way one system test will test the entire gem.

In the test/dummy app there is a complete example of a live updating component.

License

The gem is available as open source under the terms of the MIT License.

TODO

Nice to have

  • install generator that does yarn add and adds lines to stimulus controllers file
  • find a way to do collection updates, a component that lists many items
  • move the component wrapper div out of component (to avoid unsubscribe/subscribe on all updates)
  • could we do something for components that rely on multiple objects?
  • allow the listen to method to accept a list of attributes so we only get updates to relevant things