53
loading...
This website collects cookies to deliver better user experience
rails new turbo-view-components -T
cd turbo-view-components
rails g scaffold Spy name:string mission:string
bundle add view_component
rails db:create db:migrate
turbo-rails
manually.bundle add turbo-rails
rails turbo:install
view_component
and turbo-rails
installed in your application and a Spy
resource created. Once you're setup, start up your server with rails s
and head to http://localhost:3000/spies.view_component
provides:rails g component Spy spy
spy_component.rb
file and a spy_component.html.erb
file in the components
directory.spy_component.rb
is good to go out of the box. For reference, it should look like this:class SpyComponent < ViewComponent::Base
def initialize(spy:)
@spy = spy
end
end
spy_component.html.erb
contains placeholder content provided by the generator right now, so let’s update it to render information about each spy:<div id="<%= dom_id @spy %>">
<p>
<strong>Name:</strong>
<%= @spy.name %>
</p>
<p>
<strong>Mission:</strong>
<%= @spy.mission %>
</p>
<p>
<%= link_to "Show this spy", @spy %>
</p>
</div>
erb
, essentially a copy of the default content of _spy.html.erb
generated by the Rails scaffold generator we ran during application setup.spies/index.html.erb
like this:<p id="notice"><%= notice %></p>
<h1>Spy</h1>
<div id="spies">
<%= render(SpyComponent.with_collection(@spies)) %>
</div>
<%= link_to "New spy", new_spy_path %>
spy
in @spies
and render each with spy_component.html.erb
.turbo_stream_from
helper from turbo-rails. Update spies/index.html.erb
like this:<!-- Snip -->
<%= turbo_stream_from "spies" %>
<div id="spies">
<%= render(SpyComponent.with_collection(@spies)) %>
</div>
<!-- Snip -->
turbo_stream_from
helper, with spies
as the name.<turbo-cable-stream-source>
in the rendered HTML with a signed-stream-name that looks something like this:<turbo-cable-stream-source channel="Turbo::StreamsChannel" signed-stream-name="aLongSecureName"></turbo-cable-stream-source>
spies
. This id must match the target of the Turbo Stream broadcast, which defaults to the plural name of the model we are broadcasting from. If our wrapper div doesn’t have an id, the broadcast we add next will fail.models/spy.rb
to broadcast newly created spies on the spies
channel.spy.rb
like this:class Spy < ApplicationRecord
after_create_commit :append_new_record
private
def append_new_record
broadcast_append_to(
'spies',
html: ApplicationController.render(
SpyComponent.new(spy: self)
)
)
end
end
html
option added to Turbo Stream broadcast methods to render the SpyComponent instead of rendering a partial.ApplicationController.render
to render a view_component isn’t officially sanctioned by the view_component
team.view_component
folks are actively discussing an official way to add support for stream broadcasts, which you can track on this issue.config.action_controller.silence_disabled_session_errors = true