cybertrain 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@
6
6
  # Generated views stay inside the template language of docs/design.md
7
7
  # section 7: literals, @ivars, locals, helper calls, `if` and `each do`.
8
8
  require "cybertrain/ident"
9
+ require "cybertrain/shell"
9
10
  require "cybertrain/version"
10
11
 
11
12
  module Cybertrain
@@ -83,6 +84,47 @@ module Cybertrain
83
84
  /tmp/*
84
85
  !/tmp/.keep
85
86
  /log/
87
+ /public/assets/
88
+ TEXT
89
+ end
90
+
91
+ # The secrets the application reads from its environment, commented:
92
+ # a template to copy from, committed, so it never holds a value.
93
+ def self.env_example
94
+ <<~TEXT
95
+ # The secrets this application reads from its environment. This file
96
+ # is committed: copy a line into the environment (or your deploy's
97
+ # secrets) with a value, never write the value here.
98
+
99
+ # Signs the session cookie; changing it signs everyone out. Required in
100
+ # production; development and test keep one in tmp/secret_key.
101
+ # Make one with `cybertrain secret`.
102
+ # CYBERTRAIN_SECRET_KEY_BASE=
103
+
104
+ # Encrypts the columns a model declares with `encrypts`; boot fails
105
+ # without it once one does. Keep it safe: encrypted data cannot be
106
+ # read without it. To rotate, move the old key to
107
+ # CYBERTRAIN_ENCRYPTION_KEY_PREVIOUS (comma-separated) and re-save.
108
+ # CYBERTRAIN_ENCRYPTION_KEY= # cybertrain secret --hex
109
+
110
+ # Settings, not secrets. /up answers 503 "feed stale" once a
111
+ # WebSocket feed has stopped reporting; 0 turns that check off.
112
+ # CYBERTRAIN_HEALTH_FEEDS=0
113
+ # Seconds of silence after which a feed counts as stale (180).
114
+ # CYBERTRAIN_HEALTH_FEED_STALE=180
115
+
116
+ # The application's time zone (an IANA name; UTC when unset): the
117
+ # boundaries of today and this week, Date.current, l and time_tag.
118
+ # CYBERTRAIN_TIME_ZONE=Asia/Tokyo
119
+ # The IANA zone cron expressions are read in; the time zone above
120
+ # when unset.
121
+ # CYBERTRAIN_SCHEDULER_TZ=Asia/Tokyo
122
+
123
+ # Redirect http to https and mark cookies Secure (production behind
124
+ # a TLS-terminating proxy).
125
+ # CYBERTRAIN_FORCE_SSL=1
126
+ # The host names the application answers to, comma-separated.
127
+ # CYBERTRAIN_HOSTS=app.example.com
86
128
  TEXT
87
129
  end
88
130
 
@@ -117,12 +159,52 @@ module Cybertrain
117
159
  `.kamal/secrets`), commit, then `kamal setup` once and `kamal deploy`
118
160
  after that. The `Dockerfile` builds the binary inside the image.
119
161
 
162
+ `cybertrain test` runs the tests under `test/` (models, controllers,
163
+ integration, with the rows of `test/fixtures/*.yml`) as one program;
164
+ `cybertrain test test/models/post_test.rb` runs one file and
165
+ `cybertrain test -n /title/` the tests whose names match.
166
+
120
167
  On GitHub, `.github/workflows/ci.yml` installs the toolchain the
121
168
  framework commit in `spin.lock` pins and checks that `spin.lock` and
122
- `gen/` are committed and current, then runs `spin test`.
169
+ `gen/` are committed and current, then runs `cybertrain test`.
123
170
  MARKDOWN
124
171
  end
125
172
 
173
+ # config/locales/en.yml: Rails' stock comment block adapted, then one key.
174
+ def self.locales_en_yml
175
+ <<~YAML
176
+ # Files in the config/locales directory are read by `spin run gen` and
177
+ # compiled into the program; the app has no YAML at run time. Every
178
+ # *.yml under config/locales (subdirectories too) is read, and a key
179
+ # here overrides the framework's own dictionary of the same name.
180
+ #
181
+ # The first key of a file is the locale: en, ja, pt-BR. To add a language,
182
+ # add a file (config/locales/ja.yml) and list it in config/app.rb:
183
+ # c.i18n_available_locales = [:en, :ja]
184
+ #
185
+ # To look a key up, write it out in full in code, I18n.t("hello"), or
186
+ # in a template, <%= t("hello") %>. A key starting with "." in a
187
+ # template is relative to the template: in app/views/posts/index.html.erb,
188
+ # <%= t(".title") %> reads posts.index.title:
189
+ #
190
+ # en:
191
+ # posts:
192
+ # index:
193
+ # title: "Posts"
194
+ #
195
+ # Values may hold %{name} placeholders, filled from the call:
196
+ # t("greeting", name: "Ada"). A key with `one` and `other` entries
197
+ # is chosen by count: t("posts", count: 2).
198
+ #
199
+ # I18n.locale is the language of the current request (it starts as the
200
+ # default locale on each request); I18n.locale = :ja switches it.
201
+ #
202
+ # To learn more, see docs/guide/i18n.md.
203
+ en:
204
+ hello: "Hello world"
205
+ YAML
206
+ end
207
+
126
208
  def self.config_app
127
209
  <<~RUBY
128
210
  # Application settings; see Cybertrain::Config for every option.
@@ -140,12 +222,56 @@ module Cybertrain
140
222
  # Production marks the session cookie Secure (HTTPS only). Turn it
141
223
  # off only if production is really served over plain http://.
142
224
  # c.session_secure = false
225
+
226
+ # Sent with every response; "" turns the header off.
227
+ # c.permissions_policy = "camera=(), microphone=(), geolocation=()"
228
+
229
+ # Content Security Policy, off until you set it. Start in report-only
230
+ # mode, watch the browser console, then turn it on. The nonce lets
231
+ # the tags csp_meta_tag, javascript_importmap_tags and
232
+ # stylesheet_link_tag(nonce: true) through without "unsafe-inline".
233
+ # When you list style-src, add nonce: true to the layout's
234
+ # stylesheet_link_tag too, or the browser blocks the stylesheet.
235
+ # c.content_security_policy do |p|
236
+ # p.default_src :self
237
+ # p.script_src :self, "https://cdn.jsdelivr.net"
238
+ # p.style_src :self
239
+ # end
240
+ # c.content_security_policy_nonce_directives = %w[script-src style-src]
241
+ # c.content_security_policy_report_only = true
242
+
243
+ # Translations (config/locales/*.yml). The default locale starts each
244
+ # request; list more locales to accept them in I18n.locale= (and
245
+ # pass I18n.available_locales to request.preferred_locale). A
246
+ # missing key shows a marker, or raises
247
+ # with i18n_raise_on_missing. To pick the locale per request, see
248
+ # docs/guide/i18n.md (a set_locale before_action in
249
+ # ApplicationController using request.preferred_locale).
250
+ # c.i18n_default_locale = :en
251
+ # c.i18n_available_locales = [:en, :ja]
252
+ # c.i18n_raise_on_missing = true
143
253
  end
254
+
255
+ # A scheduled task: a cron expression (read in c.scheduler_tz, which
256
+ # follows c.time_zone, UTC by default, unless set), a unique name and
257
+ # a block. One process at a time leads the schedule; the web and
258
+ # worker roles both run it. Finished jobs stay in cybertrain_jobs
259
+ # until something deletes them: this one deletes the done ones a week
260
+ # old (failed ones are kept for the jobs command).
261
+ # Cybertrain::Scheduler.cron("0 4 * * *", "prune done jobs") do
262
+ # Cybertrain::Job.prune_done(Time.now.to_i - 7 * 86_400)
263
+ # end
144
264
  RUBY
145
265
  end
146
266
 
267
+ # The jobs page line is a comment: a new application has no
268
+ # require_admin. `cybertrain generate authentication` provides one (the
269
+ # Authentication concern's) and draws the page behind it
270
+ # (CLI::Authentication.enable_jobs_page), as
271
+ # jobs_page "/admin/jobs", before_action: :require_admin, skip_before_action: :require_authentication
272
+ # so that require_admin alone answers a visitor (404).
147
273
  def self.routes
148
- "Cybertrain::Routes.draw do\nend\n"
274
+ "Cybertrain::Routes.draw do\n # jobs_page \"/admin/jobs\", before_action: :require_admin\nend\n"
149
275
  end
150
276
 
151
277
  def self.schema
@@ -174,7 +300,9 @@ module Cybertrain
174
300
  <title>#{title}</title>
175
301
  <meta name="viewport" content="width=device-width,initial-scale=1">
176
302
  <%= csrf_meta_tags %>
177
- <link rel="stylesheet" href="/style.css">
303
+ <%= csp_meta_tag %>
304
+ <%= stylesheet_link_tag "application" %>
305
+ <%= javascript_importmap_tags %>
178
306
  </head>
179
307
  <body>
180
308
  <main>
@@ -198,7 +326,10 @@ module Cybertrain
198
326
  <head>
199
327
  <title>#{message} (#{status})</title>
200
328
  <meta name="viewport" content="width=device-width,initial-scale=1">
201
- <link rel="stylesheet" href="/style.css">
329
+ <style>
330
+ body { font-family: system-ui, sans-serif; line-height: 1.5; margin: 0; color: #222; }
331
+ main { max-width: 48rem; margin: 0 auto; padding: 1rem; }
332
+ </style>
202
333
  </head>
203
334
  <body>
204
335
  <main>
@@ -228,6 +359,25 @@ module Cybertrain
228
359
  CSS
229
360
  end
230
361
 
362
+ # app/javascript/application.js: the import map's entry point.
363
+ def self.application_js
364
+ <<~JS
365
+ // Entry point for the import map (config/importmap.rb).
366
+ // import "@hotwired/turbo"
367
+ JS
368
+ end
369
+
370
+ # config/importmap.rb: the pins gen reads into the import map.
371
+ def self.importmap
372
+ <<~RUBY
373
+ # Pins for the import map: a logical name from app/javascript or
374
+ # vendor/javascript, or a URL.
375
+ pin "application"
376
+ # pin "@hotwired/turbo", to: "https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.12/dist/turbo.es2017-esm.js"
377
+ # pin_all_from "app/javascript/controllers", under: "controllers"
378
+ RUBY
379
+ end
380
+
231
381
  def self.bin_app(package)
232
382
  <<~RUBY
233
383
  require "cybertrain"
@@ -305,7 +455,7 @@ module Cybertrain
305
455
  # requires prism, which 24.04's Ruby 3.2 does not bundle.
306
456
  RUN apt-get update -qq && \\
307
457
  apt-get install --no-install-recommends -y build-essential git curl ca-certificates \\
308
- ruby ruby-dev libsqlite3-dev zlib1g-dev libjemalloc-dev && \\
458
+ ruby ruby-dev libsqlite3-dev zlib1g-dev libjemalloc-dev libssl-dev && \\
309
459
  rm -rf /var/lib/apt/lists/* && \\
310
460
  gem install --no-document prism -v 1.9.0
311
461
 
@@ -321,7 +471,7 @@ module Cybertrain
321
471
  FROM docker.io/library/ubuntu:$UBUNTU_VERSION
322
472
 
323
473
  RUN apt-get update -qq && \\
324
- apt-get install --no-install-recommends -y libsqlite3-0 zlib1g libjemalloc2 && \\
474
+ apt-get install --no-install-recommends -y libsqlite3-0 zlib1g libjemalloc2 libssl3t64 && \\
325
475
  rm -rf /var/lib/apt/lists/*
326
476
 
327
477
  RUN useradd --system --create-home --shell /bin/bash app
@@ -332,9 +482,15 @@ module Cybertrain
332
482
  # storage/ holds the SQLite database (storage/production.sqlite3); mount
333
483
  # a volume there so it outlives the container.
334
484
  USER app
485
+ # SPINEL_GC_FULL_INTERVAL=8: a full collection every eighth one. Left to
486
+ # adapt, Spinel's cadence falls to nearly every collection full under a
487
+ # server's request garbage; fixed at 8 it serves about 16% more requests
488
+ # a second on one CPU at the same memory (cybertrain's
489
+ # docs/spinel-feedback.md, item 5).
335
490
  ENV CYBERTRAIN_ENV=production \\
336
491
  CYBERTRAIN_HOST=0.0.0.0 \\
337
- PORT=3000
492
+ PORT=3000 \\
493
+ SPINEL_GC_FULL_INTERVAL=8
338
494
  EXPOSE 3000
339
495
 
340
496
  # Apply pending migrations, then serve. exec hands SIGTERM to the server,
@@ -369,11 +525,39 @@ module Cybertrain
369
525
  # The image to build and push. CHANGE ME: your registry user.
370
526
  image: your-user/#{package}
371
527
 
372
- # The servers to deploy to. CHANGE ME: the server's address. One
373
- # server: the database is a SQLite file on that server's volume.
528
+ # The servers to deploy to, by role; every role runs this one image.
529
+ # CHANGE ME: the server's address. One server: the database is a
530
+ # SQLite file on that server's volume, which every role shares.
374
531
  servers:
532
+ # The app (`./#{package}`): HTTP, and also jobs, scheduled tasks and
533
+ # WebSocket feeds unless CYBERTRAIN_WORKER is 0.
375
534
  web:
376
- - 192.168.0.1
535
+ hosts:
536
+ - 192.168.0.1
537
+ # Jobs and scheduled tasks without HTTP. Several workers (and the
538
+ # web role) may share the database: one at a time leads the
539
+ # scheduled tasks, and the jobs of one that dies are picked up by
540
+ # the others.
541
+ worker:
542
+ hosts:
543
+ - 192.168.0.1
544
+ cmd: ./#{package} worker
545
+ # The process exits non-zero when it cannot boot: the container
546
+ # runtime must start it again.
547
+ options:
548
+ restart: unless-stopped
549
+ # One container per WebSocket feed (Cybertrain::WebSocket.subscribe
550
+ # names). If you use it, give web `env: clear: CYBERTRAIN_WORKER: 0`
551
+ # so that the web role does not open the same feeds too.
552
+ # feeds:
553
+ # hosts:
554
+ # - 192.168.0.1
555
+ # cmd: ./#{package} feeds trades
556
+ # # The process exits with status 1 when a feed keeps failing
557
+ # # past its restart limit: the container runtime must start it
558
+ # # again.
559
+ # options:
560
+ # restart: unless-stopped
377
561
 
378
562
  # kamal-proxy terminates TLS (a Let's Encrypt certificate for host)
379
563
  # and forwards to the app on port 3000. Keep ssl on: in production the
@@ -419,6 +603,13 @@ module Cybertrain
419
603
  volumes:
420
604
  - "#{package}_storage:/app/storage"
421
605
 
606
+ # Digested files under public/assets/ (cybertrain gen keeps the current
607
+ # digest and the two before it). Every image carries only its own, so
608
+ # this bridges the previous release's files into the new container
609
+ # for the switch-over: a page loaded before the deploy still finds
610
+ # the CSS and JavaScript its HTML names.
611
+ asset_path: /app/public/assets
612
+
422
613
  # `kamal db_status` (pending migrations) and `kamal shell`.
423
614
  aliases:
424
615
  db_status: app exec --reuse "./#{package} db status"
@@ -452,7 +643,7 @@ module Cybertrain
452
643
  TEXT
453
644
  end
454
645
 
455
- # "saeki-mototsune/cybertrain/.github/actions/setup-cybertrain@v0.3.1":
646
+ # "saeki-mototsune/cybertrain/.github/actions/setup-cybertrain@vX.Y.Z":
456
647
  # the composite action in this repository, at this CLI's release tag.
457
648
  # `uses:` takes no expressions, so the pin is static; the action itself
458
649
  # reads the framework commit out of spin.lock and installs the
@@ -488,26 +679,62 @@ module Cybertrain
488
679
  # path dependency, check the framework out yourself and pass
489
680
  # `with: { framework-path: ... }`.
490
681
  - uses: #{action}
682
+ id: cybertrain
491
683
 
492
684
  # spin.lock is committed and matches spin.toml.
493
685
  - name: spin.lock is current
494
686
  run: spin lock && git diff --exit-code spin.lock
495
687
 
496
688
  # gen/ is committed and fresh (nothing is written).
689
+ # SPIN_DEBUG=1: the mode the cybertrain CLI builds gen in.
497
690
  - name: gen/ is current
498
- run: spin run gen -- --check
691
+ run: #{Shell::TOOL_SPIN} run gen -- --check
499
692
 
500
- # `spin test` fails when there is no test/*.rb; a new app has none.
693
+ # Every test under test/, compiled into one program and run.
694
+ # The action puts spin on PATH; the cybertrain command is the
695
+ # CLI of the framework commit it fetched.
501
696
  - name: Tests
502
- run: |
503
- if ls test/*.rb > /dev/null 2>&1; then
504
- spin test
505
- else
506
- echo "no test/*.rb yet"
507
- fi
697
+ env:
698
+ CYBERTRAIN_PATH: ${{ steps.cybertrain.outputs.framework-path }}
699
+ run: ruby -I "$CYBERTRAIN_PATH" "$CYBERTRAIN_PATH/exe/cybertrain" test
508
700
  YAML
509
701
  end
510
702
 
703
+ # test/test_helper.rb (spec 5.1): what every test file's `require
704
+ # "test_helper"` loads. `cybertrain test` requires it before the test
705
+ # files; the generators that add helpers (authentication) insert them
706
+ # after TEST_HELPER_MARKER.
707
+ TEST_HELPER_MARKER = " # Helper methods used by all tests go here."
708
+
709
+ def self.test_helper
710
+ <<~RUBY
711
+ ENV["CYBERTRAIN_ENV"] ||= "test"
712
+ require_relative "../config/app"
713
+ require "cybertrain/test_help"
714
+
715
+ class ActiveSupport::TestCase
716
+ fixtures :all
717
+
718
+ #{TEST_HELPER_MARKER}
719
+ end
720
+ RUBY
721
+ end
722
+
723
+ # test/integration/health_test.rb: a new application's one test, a
724
+ # request to the health check.
725
+ def self.health_test
726
+ <<~RUBY
727
+ require "test_helper"
728
+
729
+ class HealthTest < ActionDispatch::IntegrationTest
730
+ test "the health check answers" do
731
+ get "/up"
732
+ assert_response :success
733
+ end
734
+ end
735
+ RUBY
736
+ end
737
+
511
738
  # What kamal-proxy polls before it sends traffic to a new container.
512
739
  def self.up_html
513
740
  "<!DOCTYPE html>\n<html><body>OK</body></html>\n"
@@ -542,7 +769,7 @@ module Cybertrain
542
769
  # - every instance method and reader of Cybertrain::Controller,
543
770
  # public or private (cybertrain/controller.rb);
544
771
  # - the methods the generators write into ApplicationController
545
- # (Templates.application_controller and the authentication block).
772
+ # (Templates.application_controller and the Authentication concern).
546
773
  # Names ending in ? or ! are left out: a field name cannot have them.
547
774
  # script/check-reserved-names fails when Controller or those templates
548
775
  # gain a method this list lacks. The per-model helpers (set_<model>,
@@ -550,15 +777,20 @@ module Cybertrain
550
777
  ATTACHMENT_RESERVED_ACTIONS = %w[
551
778
  index show new new_action edit create update destroy
552
779
  ctx request response params action_name rescued_exception session flash
553
- initialize process run_callback default_render view_assigns view_env
554
- controller_path render_template render redirect_to head send_blob
780
+ initialize process run_callback call_helper_method default_render view_assigns view_env
781
+ controller_path controller_layout render_template render redirect_to head send_blob send_data fresh_when expires_in stream
555
782
  run_action run_before_callbacks run_after_callbacks run_one
556
783
  rescue_with_handler render_partial send_html string_keys json_body
557
- safe_redirect_path
558
-
559
- apply_rate_limit
560
- record_not_found resume_session require_authentication
561
- start_new_session_for terminate_session after_authentication_url
784
+ safe_redirect_path apply_validators validator_key validator_time strip_weak
785
+ respond_to head_not_acceptable send_rendered format_template_path apply_vary_accept
786
+
787
+ apply_rate_limit rate_limit_key
788
+ record_not_found resume_session require_authentication require_admin
789
+ start_new_session_for session_limit terminate_session after_authentication_url mail_link_base
790
+ send_confirmation_mail
791
+ cookies
792
+ turbo_stream partial_body
793
+ t translate
562
794
  ]
563
795
 
564
796
  # Whether `field` as the name of the download action `def <field>` on
@@ -605,12 +837,154 @@ module Cybertrain
605
837
  buf << "# Columns, associations and the Cybertrain::Model superclass come from\n"
606
838
  buf << "# gen/models/#{res.singular}.rb, generated from db/schema.rb by `spin run gen`.\n"
607
839
  buf << "class #{res.class_name}\n"
840
+ res.fields.each { |f| buf << " belongs_to :#{f.field_name}\n" if f.reference? }
608
841
  first = res.first_string_field
609
842
  buf << " validates :#{first}, presence: true\n" unless first == ""
610
843
  buf << "end\n"
611
844
  buf
612
845
  end
613
846
 
847
+ # A fixture value of a field's type, as Rails' scaffold writes it
848
+ # (MyString, MyText, ...), the same in both rows. A references field
849
+ # names the parent's row `one`.
850
+ def self.fixture_value(f)
851
+ case f.field_type
852
+ when "string" then "MyString"
853
+ when "text" then "MyText"
854
+ when "integer" then "1"
855
+ when "float" then "1.5"
856
+ when "boolean" then "false"
857
+ when "date" then "2026-11-11"
858
+ when "datetime" then "2026-11-11 12:00:00"
859
+ when "references" then "one"
860
+ else ""
861
+ end
862
+ end
863
+
864
+ # test/fixtures/<plural>.yml: the rows `one` and `two`, a sample value
865
+ # per field. An attachment field has none: its columns default to
866
+ # nothing attached.
867
+ def self.fixture_file(res)
868
+ buf = +""
869
+ buf << "# The rows every test starts with: `cybertrain test` loads every file of\n"
870
+ buf << "# test/fixtures/ before each test, and #{res.plural}(:one) answers the first.\n"
871
+ ["one", "two"].each do |label|
872
+ buf << "\n#{label}:\n"
873
+ res.fields.each do |f|
874
+ buf << " #{f.field_name}: #{fixture_value(f)}\n" unless f.attachment?
875
+ end
876
+ end
877
+ buf
878
+ end
879
+
880
+ # test/models/<singular>_test.rb: the fixture is a valid record.
881
+ def self.model_test(res)
882
+ <<~RUBY
883
+ require "test_helper"
884
+
885
+ class #{res.class_name}Test < ActiveSupport::TestCase
886
+ test "the fixture is valid" do
887
+ assert #{res.plural}(:one).valid?
888
+ end
889
+ end
890
+ RUBY
891
+ end
892
+
893
+ # The params of the create and update tests: the fixture's values,
894
+ # keys sorted as Rails' scaffold sorts them. A file is never a param.
895
+ def self.controller_test_params(res)
896
+ s = res.singular
897
+ keys = Array.new(0) { "" }
898
+ res.fields.each { |f| keys << f.column_name unless f.attachment? }
899
+ pairs = keys.sort.map { |k| "#{k}: @#{s}.#{k}" }
900
+ pairs.empty? ? "{ #{s}: {} }" : "{ #{s}: { #{pairs.join(", ")} } }"
901
+ end
902
+
903
+ # What `generate authentication` writes (and nothing else does): the
904
+ # sign_in_as helper that a generated test's `sign_in_as users(:one)`
905
+ # needs. Its presence is how the scaffold and the attachment
906
+ # generators tell an application with authentication (a scaffold of
907
+ # its own `user` model writes app/models/user.rb too).
908
+ SESSION_TEST_HELPER = "test/support/session_test_helper.rb"
909
+
910
+ # Whether the application at root has `generate authentication`'s
911
+ # test helper (SESSION_TEST_HELPER).
912
+ def self.signs_in_tests?(root)
913
+ File.exist?(File.join(root, SESSION_TEST_HELPER))
914
+ end
915
+
916
+ # Whether line is the scaffold controller test's setup line
917
+ # (` @article = articles(:one)`), which `generate authentication`
918
+ # signs in before.
919
+ def self.scaffold_setup_line?(line)
920
+ return false unless line.start_with?(" @") && line.end_with?("(:one)")
921
+
922
+ eq = line.index(" = ")
923
+ !eq.nil? && line.index(" ", 5) == eq
924
+ end
925
+
926
+ # test/controllers/<plural>_controller_test.rb: Rails' scaffold test,
927
+ # one request per action, on the fixture row `one`. In an application
928
+ # with authentication (`signed_in`) every test signs the fixture user
929
+ # `one` in first (SessionTestHelper#sign_in_as).
930
+ def self.controller_test(res, signed_in = false)
931
+ s = res.singular
932
+ words = s.tr("_", " ")
933
+ index = res.index_helper
934
+ params = controller_test_params(res)
935
+ sign_in = signed_in ? " sign_in_as users(:one)\n" : ""
936
+ <<~RUBY
937
+ require "test_helper"
938
+
939
+ class #{res.plural_class}ControllerTest < ActionDispatch::IntegrationTest
940
+ setup do
941
+ #{sign_in} @#{s} = #{res.plural}(:one)
942
+ end
943
+
944
+ test "should get index" do
945
+ get #{index}_url
946
+ assert_response :success
947
+ end
948
+
949
+ test "should get new" do
950
+ get new_#{s}_url
951
+ assert_response :success
952
+ end
953
+
954
+ test "should create #{words}" do
955
+ assert_difference(-> { #{res.class_name}.count }, 1) do
956
+ post #{index}_url, params: #{params}
957
+ end
958
+
959
+ assert_redirected_to #{s}_url(#{res.class_name}.last)
960
+ end
961
+
962
+ test "should show #{words}" do
963
+ get #{s}_url(@#{s})
964
+ assert_response :success
965
+ end
966
+
967
+ test "should get edit" do
968
+ get edit_#{s}_url(@#{s})
969
+ assert_response :success
970
+ end
971
+
972
+ test "should update #{words}" do
973
+ patch #{s}_url(@#{s}), params: #{params}
974
+ assert_redirected_to #{s}_url(@#{s})
975
+ end
976
+
977
+ test "should destroy #{words}" do
978
+ assert_difference(-> { #{res.class_name}.count }, -1) do
979
+ delete #{s}_url(@#{s})
980
+ end
981
+
982
+ assert_redirected_to #{index}_url
983
+ end
984
+ end
985
+ RUBY
986
+ end
987
+
614
988
  def self.controller(res)
615
989
  s = res.singular
616
990
  p = res.plural
@@ -624,8 +998,10 @@ module Cybertrain
624
998
  # A form whose only fields are files sends no `#{s}[...]` key at all
625
999
  # when no file is chosen (the parser drops an empty file input), so
626
1000
  # `require` would make such an edit a 400: `nested` reads the absent
627
- # key as empty, and the update keeps the stored file.
628
- lookup = permit_list.empty? && res.attachments? ? "nested" : "require"
1001
+ # key as empty, and the update keeps the stored file. A scaffold with
1002
+ # no fields at all is the same case (Rails writes
1003
+ # `params.fetch(:widget, {})` there): nothing to require.
1004
+ lookup = permit_list.empty? ? "nested" : "require"
629
1005
  <<~RUBY
630
1006
  class #{res.plural_class}Controller < ApplicationController
631
1007
  before_action :set_#{s}, only: [:show, :edit, :update, :destroy]