You are here:Setup Ruby, cc, SQLite
Requirements
WhyCyberTrain compiles through Spinel to C, so it needs a C toolchain and the
SQLite headers; the cybertrain command is a gem, so it needs Ruby.
- Ruby 3.2+ and RubyGems, for the
cybertraincommand and the development server's CRuby preview (which needs Ruby'sfiddle); a deployed application never runs on CRuby. On Ruby 3.2, alsogem install prism. - Spinel, at the release CyberTrain pins (
cybertrain doctorprints it), of the saeki-mototsune/spinel fork, which carries the fixes CyberTrain needs ahead of an upstream release; untested against other versions. You do not install it by hand: the first command that needs it builds that release into~/.cybertrain(a few minutes, once), unless aspinelof that release is already onPATH. - A C toolchain (
cc, or the compilerCCnames) andmake, plusgitandcurl, to build Spinel, which compiles every program to C. - SQLite 3, zlib and OpenSSL headers and libraries:
libsqlite3-dev,zlib1g-devandlibssl-devon Debian/Ubuntu. On macOS, SQLite and zlib come with Xcode's command line tools and OpenSSL from Homebrew (brew install openssl@3, then the two paths Requirements gives).
cybertrain doctor checks all of this and prints the install command for
whatever is missing. The full list and what is optional:
Requirements; where Spinel goes and how to use
another install: how Spinel is installed.
No machine to install on? The playground opens this blog in a GitHub Codespace with steps 02, 03, 04 and 07 already done.
You are here:Setup the cybertrain CLI
Install the CLI
Whycybertrain is the command that creates apps, scaffolds resources,
migrates, serves and builds.
The first line installs it from RubyGems. The rest is the whole tutorial at a glance; the steps below take it one command at a time.
gem install cybertrain
cybertrain new blog # installs Spinel the first time (a few minutes)
cd blog
cybertrain g scaffold article title:string body:text
cybertrain db migrate
cybertrain server # http://127.0.0.1:3000
cybertrain build # production: dist/blog, dist/public/, dist/storage/, dist/tmp/
Every command, with its options, is listed in the Installing guide.
You are here:You write blog/
Create the application
WhyYou get the Rails directory conventions plus three bin/ programs:
bin/blog.rb (the app), bin/gen.rb (the generator) and bin/db.rb
(development migrations).
cybertrain new blog
cd blog
cybertrain new writes the application with its spin.toml pointing at the
release matching the CLI (X.Y.Z is what cybertrain version prints):
[package]
name = "blog"
version = "0.1.0"
[dependencies]
cybertrain = { git = "https://github.com/saeki-mototsune/cybertrain", ref = "vX.Y.Z" }
Then it makes sure Spinel is installed (the first time, that means building
the pinned Spinel release into ~/.cybertrain: a few minutes, once; see
step 00) and runs spin lock (spin fetches the framework
into its cache, ~/.cache/spin/packages/, and pins the commit in spin.lock)
and SPIN_DEBUG=1 spin run gen (gen built in spin's debug mode), much as
rails new runs bundle install, so
cybertrain server works right away. It ends by printing the next steps.
Nothing of the framework is copied into the app; commit spin.toml and
spin.lock.
If Spinel or one of the two spin steps fails, the files stay, new exits
with 1 and prints what to run once the cause is fixed (for Spinel:
cybertrain setup, then cybertrain spin lock && SPIN_DEBUG=1 cybertrain
spin run gen in the new directory). --skip-spin only writes the files; --path DIR
depends on a local checkout instead, --git URL [--ref R] on the framework
at URL (at branch or tag R), and --version V on an index version once
cybertrain is on a spin-index.
App names use lowercase letters, digits and _, starting with a letter. The
generated tree:
blog/
spin.toml config/app.rb config/routes.rb config/locales/en.yml .env.example
db/schema.rb db/migrate/
app/controllers/application_controller.rb app/models/ app/views/ app/helpers/ app/jobs/
app/assets/stylesheets/application.css app/assets/images/
app/javascript/application.js config/importmap.rb
public/ bin/blog.rb bin/gen.rb bin/db.rb
gen/ storage/ tmp/ test/ .github/workflows/ci.yml
Dockerfile config/deploy.yml .kamal/secrets
bin/blog.rb is the application's one entry point, the program
spin build blog compiles: ./blog serves, ./blog migrate and
./blog db status manage the database. bin/gen.rb runs the generator
(spin run gen), and bin/db.rb runs the migrator during development
(cybertrain db migrate uses it, since bin/blog.rb cannot compile until the
first migration has generated gen/models/). gen/ already holds what
spin run gen wrote, views.rb among it: the committed, empty table of
embedded views.
Both bin/blog.rb and bin/db.rb start with require "cybertrain/core":
the framework without its optional subsystems (jobs, Turbo Streams, the
mailer, the cache and the rest), which keeps every build shorter. The steps
below that use one add its line (Subsystems).
The layout links app/assets/stylesheets/application.css with
stylesheet_link_tag and loads app/javascript/application.js through the
import map of config/importmap.rb with javascript_importmap_tags; spin
run gen writes both digested into public/assets/, which is git-ignored
(see Assets). .env.example lists the variables the app reads,
.github/workflows/ci.yml runs the tests on GitHub
(Continuous integration), and the last
line of the tree is the Kamal setup of step 19.
ApplicationController starts like this, so a missing record maps to a 404
through rescue_from:
class ApplicationController < Cybertrain::Controller
rescue_from Cybertrain::RecordNotFound, with: :record_not_found
private
def record_not_found
render plain: "Not Found", status: :not_found
end
end
You are here:You write app/, db/migrate/
Scaffold an article
WhyOne command writes the whole CRUD slice, Rails-style.
cybertrain generate scaffold article title:string body:text
It writes a migration, a model, a controller, five views (index, show,
new, edit, _form), a fixture file and tests (step 16), and inserts resources :articles into
config/routes.rb. Field types are string, text, integer, float,
boolean, date, datetime, references and attachment (an uploaded
file, step 18); the default is string. The quick start's
cybertrain g scaffold is the same command.
Existing files are never overwritten: each file is reported as create,
identical or exist.
You are here:You write config/routes.rb
Point the root route
Why/ should show the article list.
# config/routes.rb
Cybertrain::Routes.draw do
root "articles#index"
resources :articles
# jobs_page "/admin/jobs", before_action: :require_admin
end
Routes are read at build time: spin run gen turns them into
gen/routes.rb. cybertrain server, cybertrain db migrate and
cybertrain build run it for you.
You are here:You write app/models/
Add model validations
WhyAs in Rails' guide, add a length validation by hand.
# app/models/article.rb -- only the first string field gets a default
# presence validation; add anything past that yourself.
class Article
validates :title, presence: true
validates :title, uniqueness: true
validates :body, presence: true, length: { minimum: 10 }
end
class Article has no superclass written: the Cybertrain::Model superclass,
columns and finders come from gen/models/article.rb. A failed save reports
messages such as "Title can't be blank", "Title has already been taken" and
"Body is too short (minimum is 10 characters)". The other validators
(format, inclusion, numericality, ...) are in
Validations.
You are here:You write app/controllers/
The ArticlesController
WhyFull CRUD, Rails-shaped down to strong params and flash-then-redirect, except for two things Spinel forces everywhere.
# app/controllers/articles_controller.rb (index/show/edit are as plain as
# Rails' own scaffold; update mirrors create)
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
def new_action # a `new` method would shadow ArticlesController.new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Article was successfully created."
redirect_to article_path(@article), status: :see_other
else
render :new, status: :unprocessable_entity
end
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :body)
end
end
The scaffold writes the full controller with index, show, edit, update
and destroy too; the excerpt above omits them. In index,
@articles = Article.all.to_a: the .to_a is required.
Instance variables are found by a lexical scan of @ivar =, so re-run
cybertrain spin run gen after adding one; the development server does this
for you.
You are here:Build time, then run time gen/ → build/bin/blog
Generate, migrate, run
WhyTurn schema and routes into gen/, create the SQLite database, start the
server.
cybertrain db migrate # spin run gen; spin run db -- migrate; spin run gen (gen and db in debug mode)
cybertrain server # http://127.0.0.1:3000; Ruby edits show at once (CRuby), then compiled; views need neither
spin run gen reads db/schema.rb and config/routes.rb, scans app/ and
writes gen/; spin run db -- migrate applies db/migrate/*.rb and rewrites
db/schema.rb. The order matters: the first spin run gen puts the new
migration into gen/migrations.rb, which bin/db.rb requires, and the second
builds the models from the rewritten db/schema.rb.
cybertrain server serves the app from CRuby within a second and builds it
with Spinel in the background. The first build compiles the whole app, which
takes a couple of minutes; until it is done the CRuby preview answers, and
every page says so in its bottom right corner:
=> Booting cybertrain X.Y.Z
=> preview: CRuby 3.3.6
* Listening on http://127.0.0.1:3000
=> spinel: building (log: tmp/rebuild.log)
=> preview: CRuby (0.5s)
When the build is done the server prints => spinel: ready in …s; serving
the compiled binary, and the compiled binary answers from then on. After a
Ruby edit it prints Changed and the file, answers from CRuby again at once
and builds again (The development loop).
Ctrl-C stops it.
- Re-run
cybertrain spin run genand commitgen/after touching the schema, routes, a controller's or model's callbacks and ivars, a helper, component or job, or an asset. The development server does this for you, andcybertrain spin run gen -- --checklists what is stale without writing anything. - Change the port with
cybertrain server 4000(orPORT=4000). cybertrain dbadds the--thatspin run dbneeds before its arguments;cybertrain db statusand the other database commands work the same way.
You are here:You write db/migrate/, app/
Scaffold comments
WhyThe references type gives you the foreign key that the association is
derived from.
cybertrain generate scaffold comment commenter:string body:text article:references
cybertrain db migrate # the scaffold wrote a migration for the comments table
article:references adds an article_id column, index and foreign key —
enough for Article/Comment to get their association: spin run gen reads
Article#comments and Comment#article off the foreign key. The resulting
schema:
s.create_table "comments" do |t|
t.string "commenter"
t.text "body"
t.integer "article_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
s.add_index "comments", ["article_id"], name: "index_comments_on_article_id"
s.add_foreign_key "comments", "articles", column: "article_id"
The scaffold inserts an independent resources :comments line, which the next
step replaces.
A cybertrain server left running picks the scaffold's files up as soon as
they are written, before the table exists. The new Comment model gets its
columns from gen/models/comment.rb, which gen writes only once the table
is in db/schema.rb, so the CRuby preview cannot load it (a
NoMethodError): the server answers with its own 503 page naming the
error, and the Spinel build fails too. Once cybertrain db migrate has
rewritten db/schema.rb, the server serves again.
You are here:You write config/routes.rb
Nest the routes
WhyRails' guide nests comments under articles.
Cybertrain::Routes.draw do
root "articles#index"
# A nested block takes the mapper explicitly (Spinel's instance_eval
# trampoline only rewires `self` for the outermost block): `articles.resources`.
resources :articles do |articles|
articles.resources :comments, only: [:create, :destroy]
end
# jobs_page "/admin/jobs", before_action: :require_admin
end
You are here:You write app/controllers/
The CommentsController
WhyOnly two actions are reachable, and the parent article comes from the URL
(params[:article_id]), not :id.
class CommentsController < ApplicationController
before_action :set_article
def create
@comment = Comment.new(comment_params)
@comment.article_id = @article.id
if @comment.save
flash[:notice] = "Comment was successfully created."
else
flash[:alert] = "Comment could not be saved: #{@comment.errors.full_messages.join(", ")}"
end
redirect_to article_path(@article), status: :see_other
end
def destroy
@comment = @article.comments.find(params[:id])
@comment.destroy
flash[:notice] = "Comment was successfully destroyed."
redirect_to article_path(@article), status: :see_other
end
private
def set_article
@article = Article.find(params[:article_id])
end
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
Then add validations to the comment model:
class Comment
validates :commenter, presence: true
validates :body, presence: true
belongs_to :article
end
The declared belongs_to also makes a comment without an article invalid
("Article can't be blank"), before the database would refuse it.
Article#comments is the comments' relation, so Rails'
@article.comments.find(params[:id]) works as written in destroy, and
a comment under the wrong article returns 404.
You are here:Run time app/views/, read from disk in development, embedded by cybertrain build
Views and partials
WhyThe article page lists its comments and ends with a form bound to
[@article, @comment].
First, delete the now-unreachable index, show, new and edit comment
views, and give ArticlesController#show a blank @comment:
def show
@comment = Comment.new
end
Then render the comments and the form at the end of the article page, and replace the scaffold's comment form:
<%# app/views/articles/show.html.erb %>
<h2>Comments</h2>
<% @article.comments.each do |comment| %>
<%= render "comments/comment", comment: comment %>
<% end %>
<h2>Add a comment:</h2>
<%= render "comments/form", comment: @comment %>
<%# app/views/comments/_form.html.erb %>
<%# locals: (comment:) %>
<%= form_with(model: [@article, comment]) do |f| %>
<%= f.label :commenter %> <%= f.text_field :commenter %>
<%= f.label :body %> <%= f.text_area :body %>
<%= f.submit %>
<% end %>
The comment partial:
<%# locals: (comment:) %>
<div class="comment">
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<%= button_to "Destroy comment", [@article, comment], method: :delete %>
</div>
Where the form and the button point
Both button_to ... [@article, comment] and
form_with(model: [@article, comment]) resolve through the same
[parent, child] rule: a new child routes to the nested collection
(article_comments_path), a persisted one to the nested member
(article_comment_path), both generated into gen/routes.rb from the nested
resources block above. The form takes its comment as a local, so that
step 13 can render it again with a fresh one.
You are here:You write app/components/, app/helpers/
A component and a helper
WhyFrom the next step on a comment is rendered in two places: on the page, and in a broadcast that no request is behind. A component, a class with its template beside it, renders the same in both; a helper is a method every template can call.
cybertrain generate component comment comment # the name, then its attributes: one, also called comment
cybertrain generate helper comments
The first writes app/components/comment_component.rb, with one keyword per
attribute, and its template; the second writes an empty CommentsHelper.
Each also writes a test, which step 16 comes back to. The class is
already what the blog needs:
class CommentComponent < Cybertrain::Component
def initialize(comment:)
@comment = comment
end
end
Replace the generated template with the comment's markup, and give the helper its one method:
<div class="comment" id="<%= dom_id(comment) %>">
<p><%= comment_author(comment) %> wrote:</p>
<p><%= comment.body %></p>
<%= button_to "Destroy comment", article_comment_path(comment.article_id, comment), method: :delete %>
</div>
module CommentsHelper
# The commenter's name in a <strong>, escaped: <%= comment_author(c) %>
def comment_author(comment)
name = case comment
when Comment then comment.commenter.to_s
else ""
end
Cybertrain::Html.tag("strong", { class: "comment-author" }, name)
end
end
Then render the component where the page rendered the partial, and delete
app/views/comments/_comment.html.erb:
<% @article.comments.each do |comment| %>
<%= render component: "comment", comment: comment %>
<% end %>
- The template sees the component's instance variables as locals (
comment) and its public methods without parameters by name. It is given the comment only, not the page's@article, so the button's path is built fromcomment.article_id. dom_id(comment)iscomment_7for the comment with id 7: the element id the next step's broadcasts aim at.- A component is named as a partial is, by its snake-case name without
_component: templates cannot name constants. Cybertrain::Html.tagescapes its content and returns aSafeString, which a template prints as it is; a plainStringa helper returns is escaped.
You are here:Run time Turbo Streams over Server-Sent Events
Live comments with Turbo
WhyA comment posted in one browser should appear on every open page of that article without a reload. As in a Rails 8 app, that is Turbo Streams, and there is nothing to install or to start beside the server.
Load Turbo
cybertrain new left both lines commented out; uncomment them:
pin "application"
pin "@hotwired/turbo", to: "https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.12/dist/turbo.es2017-esm.js"
import "@hotwired/turbo"
The layout's javascript_importmap_tags writes the import map and
import "application", so every page now runs Turbo
(The import map).
The server side of Turbo Streams is a subsystem: add its line under the
core's in bin/blog.rb, and the same line in bin/db.rb. Without it,
spin run gen stops at the turbo_stream_from below and names the line.
require "cybertrain/core"
require "cybertrain/streams"
Subscribe the page
Give the list and the form an id each, and subscribe the page to the article's stream:
<h2>Comments</h2>
<%= turbo_stream_from @article %>
<div id="comments">
<% @article.comments.each do |comment| %>
<%= render component: "comment", comment: comment %>
<% end %>
</div>
<h2>Add a comment:</h2>
<div id="comment_form">
<%= render "comments/form", comment: @comment %>
</div>
Broadcast and answer
create broadcasts the saved comment, then answers the browser that posted
it; destroy tells the other pages to drop the element:
def create
@comment = Comment.new(comment_params)
@comment.article_id = @article.id
unless @comment.save
flash[:alert] = "Comment could not be saved: #{@comment.errors.full_messages.join(", ")}"
redirect_to article_path(@article), status: :see_other
return
end
# Every page subscribed with turbo_stream_from @article appends the comment.
Cybertrain::Stream.broadcast_append_to(@article, target: "comments",
component: CommentComponent.new(comment: @comment))
@new_comment = Comment.new # the empty form create.turbo_stream.erb puts back
respond_to do |format|
format.turbo_stream # app/views/comments/create.turbo_stream.erb
format.html do
flash[:notice] = "Comment was successfully created."
redirect_to article_path(@article), status: :see_other
end
end
end
def destroy
@comment = @article.comments.find(params[:id])
target = Cybertrain::Html.dom_id(@comment) # read before destroy clears the id
@comment.destroy
Cybertrain::Stream.broadcast_remove_to(@article, target: target)
flash[:notice] = "Comment was successfully destroyed."
redirect_to article_path(@article), status: :see_other
end
<%= turbo_stream.append "comments", html: render(component: "comment", comment: @comment) %>
<%= turbo_stream.update "comment_form", partial: "comments/form", locals: { comment: @new_comment } %>
Open one article in two windows and post a comment in one: it appears in both, and the form that sent it comes back empty.
What happens
turbo_stream_from @articlewrites a<turbo-stream-source>element for the streamarticles:<id>, with a signed token. Turbo opens it as anEventSourceon/cybertrain/stream, which the server already serves.- A broadcast is a row in
cybertrain_messages, a table the framework creates itself. Each server process polls it and hands the row to the pages it holds, within about a tenth of a second. - Turbo submits the form asking for a Turbo Stream, so
format.turbo_streamrenderscreate.turbo_stream.erb, without a layout. A plain form post, with JavaScript off, takesformat.htmland is redirected as before. - The window that posted gets the comment twice, in the answer and in the broadcast, and shows it once: Turbo replaces an element that has the same id.
More, including WebSocket and streams for your own JavaScript: Realtime.
Turbo is fetched from jsDelivr here. To serve it yourself, copy
turbo.es2017-esm.js into vendor/javascript/ and pin it with
to: "turbo.es2017-esm.js". If you turn on the Content Security Policy
config/app.rb has commented out, its script_src must allow whichever
origin serves Turbo
(Content Security Policy).
You are here:You write app/jobs/
A background job
WhyWork that should not hold up the response, such as a notification, runs
on its own, apart from the request: it may start before the response is
written or after it. As with Active Job on Solid Queue, a job is a class in
app/jobs/ and a row in the application's own database: no other service.
cybertrain generate job notify_comment --retry StandardError:30:3
It writes app/jobs/notify_comment_job.rb, with the retry_on line the
option asked for and an empty perform, and a test, and adds
require "cybertrain/jobs" to bin/blog.rb and bin/db.rb. Fill perform in; this
one only logs, where a real application would send a mail:
class NotifyCommentJob < Cybertrain::Job::Base
retry_on StandardError, wait: 30, attempts: 3
def perform(args)
comment_id = Cybertrain::Cast.int(args["comment_id"])
article_id = Cybertrain::Cast.int(args["article_id"])
Cybertrain.logger.info("new comment #{comment_id} on article #{article_id}")
nil
end
end
Queue it from create, once the comment is saved:
NotifyCommentJob.perform_later("comment_id" => @comment.id, "article_id" => @article.id)
# Every page subscribed with turbo_stream_from @article appends the comment.
Cybertrain::Stream.broadcast_append_to(@article, target: "comments",
component: CommentComponent.new(comment: @comment))
Post a comment, and the server's log shows the job running, its lines tagged with the job and with the id of the request that queued it. Here it runs after the response; a job thread may also take the row before the response is written, so the order of the lines can differ:
2026-11-14T09:30:00.120Z INFO [3f2a9c1e-6c1d-4f0b-9a52-0d1e2f3a4b5c] Started POST "/articles/1/comments" for 127.0.0.1
2026-11-14T09:30:00.122Z INFO [3f2a9c1e-6c1d-4f0b-9a52-0d1e2f3a4b5c] Completed 200 in 2ms
2026-11-14T09:30:00.950Z INFO [NotifyCommentJob 1] [3f2a9c1e-6c1d-4f0b-9a52-0d1e2f3a4b5c] new comment 1 on article 1
2026-11-14T09:30:00.951Z INFO [NotifyCommentJob 1] [3f2a9c1e-6c1d-4f0b-9a52-0d1e2f3a4b5c] job 1 (NotifyCommentJob) done
argsis the Hash given toperform_later, stored as JSON and read back with String keys: pass ids, not records, and narrow the values withCybertrain::Cast.perform_in(seconds, args)andperform_at(time, args)queue it for later.- Jobs are rows of
cybertrain_jobs, run by three job threads of the serving process, or of a separate one started with./blog worker(Process roles). retry_on StandardError, wait: 30, attempts: 3queues a failed run again 30 seconds later, three attempts in all; the row is thenfailedand kept (Retries and discards).- A job can run more than once (a process that dies in the middle of one has
it run again), so write
performto be safe to repeat. - Failed jobs are listed, retried and discarded with
./blog jobs, or on the page the commentedjobs_pageline inconfig/routes.rbmounts once uncommented (the routes of steps 04 and 09 keep it) (The jobs page).
You are here:You write app/controllers/
Answer JSON
WhyOne action can serve the page and an API: respond_to, as in Rails.
def index
@articles = Article.all.to_a
respond_to do |format|
format.html
format.json { render json: @articles.map(&:as_json) }
end
end
def show
@comment = Comment.new
respond_to do |format|
format.html
format.json { render json: @article.as_json }
end
end
curl http://127.0.0.1:3000/articles.json
[{"id":1,"title":"Hello Rails","body":"I am on Rails! This is my first article.","created_at":"2026-11-12T10:22:45.852Z","updated_at":"2026-11-12T10:22:45.852Z"}]
- The format comes from the extension (
/articles.json) or, without one, from theAcceptheader. A format the action does not list, such as/articles.xml, is answered406 Not Acceptable. format.htmlwithout a block renders the action's template, as before.as_jsonis the record's columns, times in ISO 8601, UTC. JSON has no templates: an action answers it withrender json:.- Keep the block to its
format.lines: when a request falls back to html the block runs a second time.
/articles/1.json is one article, from the same block in show. Everything
about formats: Formats and respond_to.
You are here:Build time cybertrain test
Test it
Whyminitest and RSpec find tests by reflection, which an ahead-of-time compiler
cannot do. The tests are Rails' classes all the same: spin run gen
rewrites them into one program, which cybertrain test compiles and runs.
What the generators wrote
The scaffolds of steps 03 and 08 wrote Rails' scaffold tests:
test/fixtures/articles.yml and comments.yml (the rows one and two
every test starts with), test/models/article_test.rb and
comment_test.rb ("the fixture is valid"), and
test/controllers/articles_controller_test.rb and
comments_controller_test.rb (one request per action). Step 12 wrote
test/components/comment_component_test.rb and
test/helpers/comments_helper_test.rb, step 14
test/jobs/notify_comment_job_test.rb, and cybertrain new wrote
test/test_helper.rb, which each file requires, and
test/integration/health_test.rb, a request to /up. Three of them need the
blog as it has grown since.
Fixtures that pass the validations
The scaffold's sample values (MyString, MyText) fail step 05's
checks: two articles with one title, and bodies under ten characters. Give
the articles real ones:
one:
title: Hello Rails
body: I am on Rails! This is my first article.
two:
title: Second article
body: Another article, with no comments.
The create test posts the fixture's own title, which is now taken; give it a new one:
test "should create article" do
assert_difference(-> { Article.count }, 1) do
post articles_url, params: { article: { body: @article.body, title: "A new title" } }
end
assert_redirected_to article_url(Article.last)
end
comments.yml's rows belong to article: one. As in Rails, a fixture that
points at an article keeps the article from being deleted, so "should
destroy article" fails on the foreign key unless Article declares
has_many :comments, dependent: :destroy (the box at the end of
step 08). Add it to app/models/article.rb if you
have not, as examples/blog does:
has_many :comments, dependent: :destroy
Comments under their article
The scaffold's comments test requests the routes step 09
nested under articles, whose helpers are now article_comments_path and
article_comment_path. Replace it:
require "test_helper"
class CommentsControllerTest < ActionDispatch::IntegrationTest
test "a comment is added to its article" do
article = articles(:one)
assert_difference(-> { Comment.count }, 1) do
post article_comments_path(article), params: { comment: { commenter: "Dave", body: "First!" } }
end
assert_redirected_to article_path(article)
end
test "a comment queues its notification" do
post article_comments_path(articles(:one)), params: { comment: { commenter: "Dave", body: "First!" } }
assert_enqueued_with "NotifyCommentJob", { "comment_id" => Comment.last.id }
assert_equal 1, perform_enqueued_jobs
end
test "a form Turbo submits is answered with a Turbo Stream" do
post article_comments_path(articles(:one)), params: { comment: { commenter: "Dave", body: "First!" } },
headers: { "Accept" => "text/vnd.turbo-stream.html, text/html" }
assert_response :ok
assert_turbo_stream action: "append", target: "comments"
end
test "a destroyed comment leaves its article" do
comment = comments(:one)
assert_difference(-> { Comment.count }, -1) do
delete article_comment_path(comment.article_id, comment)
end
assert_redirected_to article_path(comment.article_id)
end
end
A test runs no job thread, so a queued job waits until the test runs it
(perform_enqueued_jobs). Forgery protection is off in tests, as in Rails,
so a post needs no token.
The component
Step 12's test renders CommentComponent with a String where the template
now expects a comment. Render the fixture comment instead:
require "test_helper"
class CommentComponentTest < ViewComponent::TestCase
test "renders the comment with its author" do
render_inline(CommentComponent.new(comment: comments(:one)))
assert_select "div.comment strong.comment-author", text: "MyString"
end
end
render_inline renders as a broadcast does, with no request, and
assert_select reads what it rendered. The other assertions:
Testing an app,
Testing jobs and
Testing streams and components.
Run the tests
cybertrain test
cybertrain test test/controllers/comments_controller_test.rb
cybertrain test -n /comment/
The first run compiles every test into one program, which takes minutes
(examples/blog's 149 tests took about nine on a 4-vCPU cloud machine). A
run with nothing changed does not compile the test program again: it may
rebuild gen once (build gen, some seconds), and then starts in well
under a second. A file or -n picks which tests run, not what is
compiled: editing any test compiles the program again. Each file prints a
heading, each test a line (ok, or FAIL and ERR with the test's line
and the message), then the totals, with whatever the code under test
prints itself (a command's output line, say) between them; the exit
status is 1 when one failed. Measured on 2026-11-13, the tutorial's blog
at this step runs 17 tests and 25 assertions.
Before each test every table is emptied and the fixtures inserted
again, so tests do not depend on each other. gen/tests.rb and
gen/test/ are generated: commit them with the rest of gen/.
You are here:You write app/, db/migrate/, config/routes.rb, test/
Add sign-in
WhySo far anyone can edit or delete an article. Like Rails 8’s
bin/rails generate authentication, one command adds email-and-password
sign-in, written as code the app owns rather than installed as an engine.
cybertrain generate authentication
cybertrain db migrate # creates the users and sessions tables
It writes the users and sessions migrations and models, the
Authentication concern, which it includes into ApplicationController,
controllers and views for signing in, signing up, resetting a password and
the account page, a mailer, the ./blog user command, and tests. It also
adds the routes, a sessions/_nav partial at the top of the layout, and a
base_url setting in config/app.rb, where links in mails start, and the
lines of the subsystems its code uses to bin/blog.rb and bin/db.rb:
cybertrain/jobs (the jobs page and the thread that sends mail),
cybertrain/mailer, cybertrain/mailer/later (mails go out with
deliver_later) and cybertrain/rate_limit (sign-in attempts are rate
limited, below). Every file is listed in
Authentication.
module Authentication
extend ActiveSupport::Concern
included do
before_action :resume_session # sets @current_user and @current_session
before_action :require_authentication # 303 to /session/new unless signed in
helper_method :authenticated?
end
From now on every action needs a signed-in user, and a visitor is redirected
to /session/new. Open the pages anyone may read again, as Rails’ guide
does:
class ArticlesController < ApplicationController
allow_unauthenticated_access only: [:index, :show]
before_action :set_article, only: [:show, :edit, :update, :destroy]
resume_session still runs on those pages, so templates can read
@current_user. Hide what a visitor cannot use:
<% if @current_user %>
<%= button_to "Destroy this article", article_path(@article), method: :delete %>
<% end %>
<% if @current_user %>
<h2>Add a comment:</h2>
<div id="comment_form">
<%= render "comments/form", comment: @comment %>
</div>
<% end %>
The comment component keeps its "Destroy comment" button for everyone: a
broadcast renders it once for all viewers, with no request and so no current
user. A visitor who clicks it is sent to the sign-in page, since
CommentsController opens no action; new comments still reach a visitor's
page, because the stream is not an action of a controller.
Start the server and open http://127.0.0.1:3000/sign_up to create the first
user. Rails’ generator has no sign-up page and leaves that to the
console; CyberTrain writes RegistrationsController, so the first user signs
up in the browser. For an invitation-only app, run the generator with
--invite-only instead: there is no sign-up page, and the first user comes
from ./blog user EMAIL or from a /setup page only the server's own
machine can open
(Sign-up, or invite-only).
The sign-in page also links to a password reset by mail, and the nav to an
account page; the Authentication guide covers them,
with lockout, "keep me signed in", --confirmable and admin users. A reset
mail needs the SMTP settings and, in production, BLOG_BASE_URL
(Links in mails).
Update the tests
Any step 16 test that opens a form, submits one, or reaches an
action other than index and show now meets the sign-in page instead. The
generator wrote test/fixtures/users.yml (one and two, whose password
is "password") and test/support/session_test_helper.rb, whose
sign_in_as test/test_helper.rb now gives every integration test, and
the generator added the sign-in to the articles test's setup (it prints insert
test/controllers/articles_controller_test.rb (sign_in_as users(:one))), so
you will find:
setup do
sign_in_as users(:one)
@article = articles(:one)
end
The comments test has no setup for the generator to add to, and every
action of CommentsController (create and destroy) now needs a signed-in
user, so each of its four tests does too; give it one:
class CommentsControllerTest < ActionDispatch::IntegrationTest
setup do
sign_in_as users(:one)
end
A scaffold generated from now on signs in by itself.
The generator's own tests (test/controllers/sessions_controller_test.rb,
registrations_controller_test.rb, passwords_controller_test.rb,
accounts_controller_test.rb, test/integration/remember_me_test.rb,
lockout_test.rb, admin_test.rb, Testing)
run with the rest under cybertrain test, moving the clock with
travel_to to check day 15 and day 30. Sign-in attempts are rate
limited as in Rails' generator, ten per client address every three
minutes, counted in the application's database so that every process
counts together; behind a reverse proxy, configure
trusted proxies.
examples/blog takes this step with --invite-only and makes its
/admin pages admin-only.
You are here:You write app/, db/migrate/, config/routes.rb, test/
Add a cover image
WhyAn article can carry a picture. The same split as sign-in: the framework
parses multipart/form-data and stores the bytes, and one command writes
the rest as code the app owns, in place of Active Storage’s
has_one_attached.
The image will be shown on the article page, which visitors may read since
step 17, so its download has to be open to them too. Before running the
generator, add :cover to the list step 17 wrote:
allow_unauthenticated_access only: [:index, :show, :cover]
cybertrain generate attachment article cover # a new model: generate scaffold NAME field:type ... cover:attachment
cybertrain db migrate # adds the cover_* columns to articles
It writes a migration that adds five columns to articles (cover_key,
cover_filename, cover_content_type, cover_byte_size, cover_checksum;
the file itself is not in SQLite) and a block in Article with cover_file=,
cover_attached?, cover_url, a validation and save and destroy callbacks.
In ArticlesController it adds a cover action behind
before_action :set_article and one line in create and in update:
class ArticlesController < ApplicationController
allow_unauthenticated_access only: [:index, :show, :cover] # step 17 wrote [:index, :show]; you added :cover
before_action :set_article, only: [:show, :edit, :update, :destroy, :cover]
# GET /articles/1/cover -- @article comes from before_action :set_article, so
# the download is scoped exactly like show (and authentication applies).
# send_blob is the one way to serve uploads: it sets the type from what the
# server detected, nosniff, a locked-down CSP and Content-Disposition
# (inline for images only, a download otherwise).
def cover
if @article.cover_attached? && Cybertrain::BlobStore.exist?(@article.cover_key)
send_blob(Cybertrain::BlobStore.read(@article.cover_key), filename: @article.cover_filename, content_type: @article.cover_content_type)
else
head 404
end
end
# ...
def create
@article = Article.new(article_params)
@article.cover_file = params.nested(:article).upload(:cover)
if @article.save
# ...
def update
@article.cover_file = params.nested(:article).upload(:cover)
if @article.update(article_params)
The download finds its article through set_article, as show does, so
whatever set_article does to limit which articles a user may see limits the
download too. Among its lines the generator prints a warning, because this
show has code of its own:
warning: app/controllers/articles_controller.rb: def show has code of its own, which def cover does not run; if that code limits who may see articles, check the same in def cover
Here that code builds a comment and picks a format; it refuses nobody, so
there is nothing to copy into cover.
The generator also adds get "/articles/:id/cover" to config/routes.rb,
multipart: true and a file input to the form, above the submit button, and
the image to the show page, right after the <h1>:
<%= form_with(model: article, multipart: true) do |f| %>
<%# ... %>
<div class="field">
<%= f.label :cover %>
<%= f.file_field :cover, accept: "image/png,image/jpeg,image/gif,image/webp" %>
</div>
<h1>Article</h1>
<% if @article.cover_attached? %><p><img src="<%= @article.cover_url %>" alt="<%= @article.cover_filename %>"></p><% end %>
The generator copies the access rules of show to the download, and only
those it can read: the callbacks. A before_action other than set_article
that lists :show without the new action stops it with cannot preserve
show's authorization for :cover, and nothing is written. Code inside
def show it cannot read for what it checks, hence the warning. With an
empty show it adds :cover to allow_unauthenticated_access by itself
where :show is listed; with code in show it leaves the line alone, and
without :cover there the image needs a sign-in.
How files are served
- Types. By default only PNG, JPEG, GIF and WebP up to 2 MB are accepted
(
COVER_TYPESandCOVER_MAX_BYTESin the model;--anyaccepts any type). The type is detected from the file’s first bytes, never taken from the browser. - Storage. The bytes go to
storage/uploads/<2 hex>/<32 hex key>(Cybertrain::BlobStore, mode 0600). Replacing a file deletes the old one, and destroying the article deletes its file. Back upstorage/uploads/together with the SQLite file. - Serving. Files go out through
send_blobin the controller, never frompublic/. The four image types are served inline; anything else is a download (application/octet-stream). Every response carriesX-Content-Type-Options: nosniffandContent-Security-Policy: default-src 'none'; sandbox. - Params.
params.nested(:article).upload(:cover)is aCybertrain::UploadedFile, or nil when no file was chosen.permitnever returns files, so a file can only arrive through that explicit line. The CSRF token is read from multipart bodies like any form’s. A broken or oversize body is a 400;max_upload_bytesandmax_multipart_partsinconfig/app.rbset the limits, andupload_rootthe directory.
Start the server, edit an article and choose an image. The generator also
wrote test/integration/article_cover_attachment_test.rb and the image
test/fixtures/files/cover.png, which test the whole flow and sign
in first now that the app has a User. Since :cover is public here, it
checks that a visitor can download the cover, and it fills the body with
"A article.", stretched to the 10-character minimum from
step 05.
Run cybertrain test as in step 16 (measured on 2026-11-13,
the tutorial's blog then runs 83 tests and 870 assertions). examples/blog has this
step too, and keeps the cover_* columns out of its JSON
(Article#public_json). Not built yet: several files per field, S3 or other remote
storage, image variants, and streaming large bodies to disk (the whole body
is read into memory, up to max_body_bytes).
You are here:Run time dist/blog
Build for deployment
WhyOne command builds the app into a deployable dist/ folder, with every view
embedded.
cybertrain build
This writes dist/: the app binary with every view embedded, plus the files
it uses beside it. It runs SPIN_DEBUG=1 spin run gen -- --embed-views,
spin build blog and SPIN_DEBUG=1 spin run gen (which puts the committed, empty gen/views.rb back, even
after a failure or Ctrl-C), then assembles:
dist/blogthe compiled framework, controllers, models and template interpreter, with every view embeddeddist/public/static assets and error pages, or let a reverse proxy serve itdist/storage/created empty; the SQLite file by default (a rebuild never empties it)dist/tmp/created empty (a rebuild never empties it)
Copy dist/ to a machine with the same OS and CPU (the binary links the
system SQLite) and run it there. A built binary is production by default
(CYBERTRAIN_ENV overrides). Set CYBERTRAIN_SECRET_KEY_BASE
(cybertrain secret prints one too); for illustration:
cd dist
export CYBERTRAIN_SECRET_KEY_BASE="$(openssl rand -hex 32)"
./blog migrate && ./blog
./blog migrate applies the migrations compiled into the binary, and
./blog db status shows their status; PORT sets the port. Keep the secret
the same across restarts: changing it ends every session. ./blog help lists
the binary's other commands, among them worker, jobs, console and
db backup.
Cybertrain::Config reads the environment first; config/app.rb overrides.
The variables a first deploy meets (all of them:
Configuration):
| Variable | Attribute | Default |
|---|---|---|
CYBERTRAIN_ENV | env | "development"; "production" in a binary from cybertrain build (also "test") |
PORT | port | 3000 |
CYBERTRAIN_DATABASE | database_path | storage/#{env}.sqlite3 |
CYBERTRAIN_SECRET_KEY_BASE | secret_key_base | required in production; dev/test auto-generate one into tmp/secret_key |
SPINEL_WORKERS | workers | 1 |
CYBERTRAIN_HOST | host | "127.0.0.1"; 0.0.0.0 listens on every interface (containers) |
CYBERTRAIN_SESSION_SAME_SITE | session_same_site | "Lax"; also Strict or None (None always adds Secure); anything else stops the server at boot |
CYBERTRAIN_SESSION_PARTITIONED | session_partitioned | false; 1 or true adds Partitioned (and Secure) |
# config/app.rb
Cybertrain.configure do |c|
c.port = 3000
c.workers = 1
end
- The server speaks plain HTTP/1.1: put nginx or Caddy in front for TLS and
HTTP/2. The session cookie is
Securein production, so serve it over HTTPS (setc.session_secure = falseinconfig/app.rbonly if production really is plain http). Behind such a proxy,CYBERTRAIN_FORCE_SSL=1redirects http to https andCYBERTRAIN_HOSTSnames the hosts the app answers to (hosts andforce_ssl). - The serving process also runs the jobs, the scheduled tasks and the stream
poller of steps 13 and 14: one process is a whole deployment.
./blog workermoves the jobs into a process of their own (Process roles). - Production refuses to start without
CYBERTRAIN_SECRET_KEY_BASE. - In production an exception answers 500, and a bare error response (the
router's plain-text 404,
head :not_found,render plain:) is replaced bypublic/<status>.htmlwhen that file exists;cybertrain newwrites404.htmland500.html. SIGTERMstops accepting, lets requests in flight finish and exits when they are done, or after the server'sdrain_timeout(10 s).- The watcher, the CRuby preview and the rebuild loop never run in
production. A running
cybertrain serverregenerates and restarts nothing whilecybertrain buildholdstmp/cybertrain-build.lock.
cybertrain new also writes a Kamal 2 setup. The
Dockerfile runs cybertrain setup and cybertrain build in an Ubuntu build
stage and copies dist/ into a slim stage of the same release, which migrates
on boot and then serves on 0.0.0.0:3000. Beside it are .dockerignore,
config/deploy.yml (kamal-proxy with Let’s Encrypt in front, the health
check on public/up.html, the SQLite file on a volume at /app/storage) and
.kamal/secrets, which reads KAMAL_REGISTRY_PASSWORD and
CYBERTRAIN_SECRET_KEY_BASE from the environment. Fill in the values marked
CHANGE ME in config/deploy.yml, commit, then:
kamal setup # first time: installs Docker and kamal-proxy on the server, builds, pushes and starts
kamal deploy # every deploy after that
The binary is compiled inside the image, so it always matches the
image’s OS; set builder.arch in config/deploy.yml to the
server’s CPU. Deploy to one server: the database is a SQLite file on
that server’s volume. Part 8 of
docs/deploy.md (Japanese; in
English, docs/deploy-kamal.md) walks through
it, backups included.
The finished app, examples/blog,
carries this setup with one difference: it builds against the framework in the
repository (path = "../.." in its spin.toml), so its Dockerfile runs
cybertrain setup and cybertrain build from the checkout instead of
installing the gem, and the build context is the repository root
(builder.context: ../.., with Dockerfile.dockerignore sending only the
framework and the app). CI
(blog-image.yml) builds that image
for every release, checks the health check, an article created through the form,
a clean stop and the database kept on its volume, and loads
config/deploy.yml with Kamal.
How these pieces fit together, and Kamal compared with a server behind Caddy, are on the deploy page.
Things to know
WhyLimits and quirks worth knowing before they surprise you.
- Sessions hold Strings only, in an encrypted cookie.
- SQLite only, through Spinel’s FFI.
- No backtraces: errors show class, message, request line and template name/line.
- A misspelled attribute in a view raises (
undefined method 'titel' for Article); a column that holdsnilrenders empty. - Associations come from foreign keys or one-line declarations; no
has_many :through, nestedincludes, enums, STI or polymorphic associations. - No
constraintsormount; JSON is answered withrender json:(there are no JSON templates). - Only the first string field gets a default presence validation in a scaffolded model.
- The generator uses a lexical scan (regexes), not a parser, over
app/controllers,app/models,app/helpers,app/componentsandapp/jobs. - Jobs run at least once, and a broadcast reaches only the pages open when it is sent, or reconnecting within a minute.
- Views are embedded at build time: a view-only change needs
cybertrain buildand a restart before it reaches production. - Build
dist/on the same OS and CPU as the machine that runs it: the binary links the system SQLite. SPINEL_WORKERSdefaults to1.- Only the pinned Spinel release (
Cybertrain::SPINEL_TAG) is tested. - More differences from Rails, in one table: Differences from Rails.