cybertrain 0.2.0 → 0.3.0

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.
@@ -5,6 +5,9 @@
5
5
  # The scaffold templates take a Cybertrain::CLI::Resource (cli/scaffold.rb).
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
+ require "cybertrain/ident"
9
+ require "cybertrain/version"
10
+
8
11
  module Cybertrain
9
12
  module CLI
10
13
  module Templates
@@ -39,19 +42,12 @@ module Cybertrain
39
42
  nil
40
43
  end
41
44
 
42
- # A lowercase Ruby-ish name: "post", "blog_post", "released_on".
45
+ # A lowercase Ruby-ish name: "post", "blog_post", "released_on". The
46
+ # snake_case subset of Ident.column? (what the generator accepts),
47
+ # letter-first since it names packages, binaries and files too; one
48
+ # definition of the characters, so the two cannot drift apart.
43
49
  def self.identifier?(word)
44
- return false if word == ""
45
-
46
- ok = true
47
- first = true
48
- word.each_char do |ch|
49
- lower = ch >= "a" && ch <= "z"
50
- digit = ch >= "0" && ch <= "9"
51
- ok = false unless lower || (!first && (digit || ch == "_"))
52
- first = false
53
- end
54
- ok
50
+ Ident.snake_case?(word, false)
55
51
  end
56
52
 
57
53
  # "blog_posts" -> "Blog posts"
@@ -67,6 +63,11 @@ module Cybertrain
67
63
  [package]
68
64
  name = "#{package}"
69
65
  version = "0.1.0"
66
+ # jemalloc is a faster malloc for a server: 1.1 to 1.4 times the
67
+ # requests per second on examples/blog (docs/benchmark.md). Building then
68
+ # needs its development package (libjemalloc-dev on Debian/Ubuntu,
69
+ # `brew install jemalloc` on macOS).
70
+ # allocator = "jemalloc"
70
71
 
71
72
  [dependencies]
72
73
  cybertrain = #{framework_dep}
@@ -78,6 +79,7 @@ module Cybertrain
78
79
  /build/
79
80
  /dist/
80
81
  /storage/*.sqlite3*
82
+ /storage/uploads/
81
83
  /tmp/*
82
84
  !/tmp/.keep
83
85
  /log/
@@ -108,6 +110,16 @@ module Cybertrain
108
110
  To deploy, copy `dist/` to a machine with the same OS and CPU, then
109
111
  `cd dist && ./#{package} migrate && ./#{package}` (production by default;
110
112
  set CYBERTRAIN_SECRET_KEY_BASE).
113
+
114
+ Or deploy with [Kamal](https://kamal-deploy.org): fill in the values
115
+ marked CHANGE ME in `config/deploy.yml`, export
116
+ KAMAL_REGISTRY_PASSWORD and CYBERTRAIN_SECRET_KEY_BASE (read by
117
+ `.kamal/secrets`), commit, then `kamal setup` once and `kamal deploy`
118
+ after that. The `Dockerfile` builds the binary inside the image.
119
+
120
+ On GitHub, `.github/workflows/ci.yml` installs the toolchain the
121
+ framework commit in `spin.lock` pins and checks that `spin.lock` and
122
+ `gen/` are committed and current, then runs `spin test`.
111
123
  MARKDOWN
112
124
  end
113
125
 
@@ -115,11 +127,16 @@ module Cybertrain
115
127
  <<~RUBY
116
128
  # Application settings; see Cybertrain::Config for every option.
117
129
  # Environment variables (PORT, CYBERTRAIN_ENV, CYBERTRAIN_DATABASE,
118
- # CYBERTRAIN_SECRET_KEY_BASE) are read before this block runs.
130
+ # CYBERTRAIN_SECRET_KEY_BASE, CYBERTRAIN_HOST, CYBERTRAIN_SESSION_SAME_SITE,
131
+ # CYBERTRAIN_SESSION_PARTITIONED, CYBERTRAIN_ALLOWED_HOSTS) are read before this block runs.
119
132
  Cybertrain.configure do |c|
120
133
  # c.port = 3000
121
134
  # c.workers = 1
122
135
 
136
+ # Development accepts localhost, 127.0.0.1 and [::1]. Add an exact
137
+ # forwarding hostname here or via CYBERTRAIN_ALLOWED_HOSTS (comma-separated).
138
+ # c.allowed_hosts << "my-preview.example.com"
139
+
123
140
  # Production marks the session cookie Secure (HTTPS only). Turn it
124
141
  # off only if production is really served over plain http://.
125
142
  # c.session_secure = false
@@ -219,6 +236,14 @@ module Cybertrain
219
236
  require_relative "../gen/app"
220
237
  require_relative "../gen/migrations"
221
238
 
239
+ # Operational commands: `./#{package} NAME ARGS...` runs the block with
240
+ # Cybertrain::DB connected (pool of 1) and exits with its value;
241
+ # `./#{package} help` lists them.
242
+ # Cybertrain::Main.command("prune", "delete old comments") do |argv|
243
+ # Cybertrain::DB.with { |c| c.execute("DELETE FROM comments WHERE created_at < date('now', '-30 days')") }
244
+ # 0
245
+ # end
246
+
222
247
  exit(Cybertrain::Main.run("#{package}", ARGV,
223
248
  router: Gen::Routes.build(Cybertrain::Router.new),
224
249
  url_resolver: Gen::Routes.url_resolver,
@@ -247,6 +272,319 @@ module Cybertrain
247
272
  RUBY
248
273
  end
249
274
 
275
+ # ---- Kamal (docs/deploy.md, "Kamal でデプロイする") ------------------
276
+ #
277
+ # The image compiles the app inside the build stage, so the binary
278
+ # links the same libc and SQLite as the runtime stage: both stages are
279
+ # the same Ubuntu release (its apt Ruby is 3.2, what the CLI needs).
280
+ # The gem is pinned to this CLI's version, the release `new` writes into
281
+ # spin.toml, so the generator that runs in the image matches the
282
+ # framework spin.lock fixes.
283
+
284
+ def self.dockerfile(package)
285
+ <<~DOCKERFILE
286
+ # syntax=docker/dockerfile:1
287
+ # The production image `kamal deploy` builds and runs (config/deploy.yml).
288
+ # To try it by hand:
289
+ # docker build -t #{package} .
290
+ # docker run --rm -p 127.0.0.1:3000:3000 -e CYBERTRAIN_SECRET_KEY_BASE=$(openssl rand -hex 32) \\
291
+ # -v #{package}_storage:/app/storage #{package}
292
+ # then open http://localhost:3000 (the session cookie is Secure in
293
+ # production; Chrome and Firefox accept it from localhost over http).
294
+ #
295
+ # The framework is fetched by spin from what spin.toml names (a git tag
296
+ # by default); an app created with --path needs a git or version
297
+ # dependency before it can be built here.
298
+
299
+ ARG UBUNTU_VERSION=24.04
300
+
301
+ # ---- build: Spinel, then `cybertrain build` -> /src/dist ----------------
302
+ FROM docker.io/library/ubuntu:$UBUNTU_VERSION AS build
303
+
304
+ # ruby-dev and the prism gem: Spinel's build runs a Ruby generator that
305
+ # requires prism, which 24.04's Ruby 3.2 does not bundle.
306
+ RUN apt-get update -qq && \\
307
+ apt-get install --no-install-recommends -y build-essential git curl ca-certificates \\
308
+ ruby ruby-dev libsqlite3-dev zlib1g-dev libjemalloc-dev && \\
309
+ rm -rf /var/lib/apt/lists/* && \\
310
+ gem install --no-document prism -v 1.9.0
311
+
312
+ # The cybertrain command, then the Spinel release it pins: a few minutes,
313
+ # cached as a layer until the version changes.
314
+ RUN gem install cybertrain -v #{Cybertrain::VERSION} --no-document && cybertrain setup
315
+
316
+ WORKDIR /src
317
+ COPY . .
318
+ RUN cybertrain build
319
+
320
+ # ---- runtime: the binary, public/ and the libraries it links ----------
321
+ FROM docker.io/library/ubuntu:$UBUNTU_VERSION
322
+
323
+ RUN apt-get update -qq && \\
324
+ apt-get install --no-install-recommends -y libsqlite3-0 zlib1g libjemalloc2 && \\
325
+ rm -rf /var/lib/apt/lists/*
326
+
327
+ RUN useradd --system --create-home --shell /bin/bash app
328
+
329
+ WORKDIR /app
330
+ COPY --from=build --chown=app:app /src/dist/ /app/
331
+
332
+ # storage/ holds the SQLite database (storage/production.sqlite3); mount
333
+ # a volume there so it outlives the container.
334
+ USER app
335
+ ENV CYBERTRAIN_ENV=production \\
336
+ CYBERTRAIN_HOST=0.0.0.0 \\
337
+ PORT=3000
338
+ EXPOSE 3000
339
+
340
+ # Apply pending migrations, then serve. exec hands SIGTERM to the server,
341
+ # which finishes the requests in flight before it exits.
342
+ CMD ["sh", "-c", "./#{package} migrate && exec ./#{package}"]
343
+ DOCKERFILE
344
+ end
345
+
346
+ def self.dockerignore
347
+ <<~TEXT
348
+ # What the image build does not need (see Dockerfile).
349
+ /.git/
350
+ /.kamal/
351
+ /build/
352
+ /dist/
353
+ /log/
354
+ /storage/*
355
+ !/storage/.keep
356
+ /tmp/*
357
+ !/tmp/.keep
358
+ TEXT
359
+ end
360
+
361
+ def self.deploy_yml(package)
362
+ <<~YAML
363
+ # Kamal 2 (https://kamal-deploy.org): `kamal setup` the first time,
364
+ # `kamal deploy` after that. Replace every value marked CHANGE ME.
365
+
366
+ # Name of the application; names its containers.
367
+ service: #{package}
368
+
369
+ # The image to build and push. CHANGE ME: your registry user.
370
+ image: your-user/#{package}
371
+
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.
374
+ servers:
375
+ web:
376
+ - 192.168.0.1
377
+
378
+ # kamal-proxy terminates TLS (a Let's Encrypt certificate for host)
379
+ # and forwards to the app on port 3000. Keep ssl on: in production the
380
+ # session cookie is Secure, so forms only work over HTTPS. CHANGE ME:
381
+ # host, with a DNS record pointing at the server.
382
+ proxy:
383
+ ssl: true
384
+ host: #{package}.example.com
385
+ app_port: 3000
386
+ healthcheck:
387
+ # public/up.html, served by the app itself.
388
+ path: /up.html
389
+
390
+ # How long kamal-proxy polls /up.html on a new container before giving
391
+ # up (Kamal's default, written out). If the new container does not
392
+ # answer 200 in time, the deploy fails and traffic stays on the old one.
393
+ deploy_timeout: 30
394
+
395
+ # Credentials for the registry the image is pushed to. CHANGE ME:
396
+ # the user; the password comes from .kamal/secrets.
397
+ registry:
398
+ # server: ghcr.io
399
+ username: your-user
400
+ password:
401
+ - KAMAL_REGISTRY_PASSWORD
402
+
403
+ # The app's settings (cybertrain/config.rb). Secrets come from
404
+ # .kamal/secrets.
405
+ env:
406
+ clear:
407
+ # kamal-proxy runs in its own container and connects from its address
408
+ # on the Docker network (Docker hands those out of 172.16.0.0/12 by
409
+ # default): trust the X-Forwarded-For it sets, so that
410
+ # request.client_ip, what rate_limit counts, is each visitor rather
411
+ # than the proxy. Change it if your Docker networks use another range.
412
+ CYBERTRAIN_TRUSTED_PROXIES: 172.16.0.0/12
413
+ # SPINEL_WORKERS: 2
414
+ secret:
415
+ - CYBERTRAIN_SECRET_KEY_BASE
416
+
417
+ # The SQLite database lives in storage/: keep it on the server across
418
+ # deploys. Back it up from there (docs/deploy.md).
419
+ volumes:
420
+ - "#{package}_storage:/app/storage"
421
+
422
+ # `kamal db_status` (pending migrations) and `kamal shell`.
423
+ aliases:
424
+ db_status: app exec --reuse "./#{package} db status"
425
+ shell: app exec --interactive --reuse "bash"
426
+
427
+ # The image compiles the app (and Spinel, once) inside Docker. Build for
428
+ # the server's CPU; building another architecture under emulation is
429
+ # slow, so on an arm64 Mac either build on the server
430
+ # (remote: ssh://root@192.168.0.1) or set arch to arm64 for an arm64
431
+ # server.
432
+ builder:
433
+ arch: amd64
434
+ # remote: ssh://root@192.168.0.1
435
+ YAML
436
+ end
437
+
438
+ def self.kamal_secrets
439
+ <<~TEXT
440
+ # Secrets for config/deploy.yml, read from the environment of the
441
+ # machine running kamal (or a password manager:
442
+ # https://kamal-deploy.org/docs/commands/secrets/). Never write the
443
+ # values themselves here: this file is committed.
444
+
445
+ # A token that can push to the registry (Docker Hub access token, or a
446
+ # GitHub token with write:packages for ghcr.io).
447
+ KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD
448
+
449
+ # Signs the session cookie; changing it signs everyone out. Generate it
450
+ # once with `openssl rand -hex 32` and keep it somewhere safe.
451
+ CYBERTRAIN_SECRET_KEY_BASE=$CYBERTRAIN_SECRET_KEY_BASE
452
+ TEXT
453
+ end
454
+
455
+ # "saeki-mototsune/cybertrain/.github/actions/setup-cybertrain@v0.3.0":
456
+ # the composite action in this repository, at this CLI's release tag.
457
+ # `uses:` takes no expressions, so the pin is static; the action itself
458
+ # reads the framework commit out of spin.lock and installs the
459
+ # toolchain that commit pins (docs/design.md D32).
460
+ def self.setup_action_ref
461
+ slug = Cybertrain::REPOSITORY.sub("https://github.com/", "")
462
+ "#{slug}/.github/actions/setup-cybertrain@v#{Cybertrain::VERSION}"
463
+ end
464
+
465
+ # .github/workflows/ci.yml: the toolchain from the setup-cybertrain
466
+ # action, then the checks an app's CI needs: spin.lock and gen/ are
467
+ # committed and current, and the tests pass.
468
+ def self.ci_workflow
469
+ action = setup_action_ref
470
+ <<~YAML
471
+ name: CI
472
+
473
+ on:
474
+ push:
475
+ branches: [main]
476
+ pull_request:
477
+
478
+ jobs:
479
+ test:
480
+ runs-on: ubuntu-latest
481
+ steps:
482
+ - uses: actions/checkout@v4
483
+
484
+ # SQLite, zlib and OpenSSL headers, Ruby, and Spinel (cached),
485
+ # installed by the cybertrain CLI of the framework commit in
486
+ # spin.lock: that commit is read from spin.lock, so the
487
+ # spin.toml dependency must be a git one (the default). With a
488
+ # path dependency, check the framework out yourself and pass
489
+ # `with: { framework-path: ... }`.
490
+ - uses: #{action}
491
+
492
+ # spin.lock is committed and matches spin.toml.
493
+ - name: spin.lock is current
494
+ run: spin lock && git diff --exit-code spin.lock
495
+
496
+ # gen/ is committed and fresh (nothing is written).
497
+ - name: gen/ is current
498
+ run: spin run gen -- --check
499
+
500
+ # `spin test` fails when there is no test/*.rb; a new app has none.
501
+ - 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
508
+ YAML
509
+ end
510
+
511
+ # What kamal-proxy polls before it sends traffic to a new container.
512
+ def self.up_html
513
+ "<!DOCTYPE html>\n<html><body>OK</body></html>\n"
514
+ end
515
+
516
+ # ---- cybertrain generate attachment / scaffold FIELD:attachment ----
517
+
518
+ # The accept= attribute of the file input: the four raster types
519
+ # Cybertrain::UploadedFile serves inline (the generator's default).
520
+ ATTACHMENT_ACCEPT = "image/png,image/jpeg,image/gif,image/webp"
521
+
522
+ # The columns an attachment field adds to its table, as [suffix, type,
523
+ # SQL default]: `cover` -> cover_key, cover_filename, cover_content_type,
524
+ # cover_byte_size, cover_checksum. NOT NULL with "" / 0 as the "nothing
525
+ # attached" value, because nullable columns cost Spinel its type
526
+ # inference (NOTES rules 7/11).
527
+ ATTACHMENT_COLUMNS = [
528
+ ["key", "string", "''"],
529
+ ["filename", "string", "''"],
530
+ ["content_type", "string", "''"],
531
+ ["byte_size", "integer", "0"],
532
+ ["checksum", "string", "''"]
533
+ ]
534
+
535
+ # Names an attachment field may not have: the generator adds `def
536
+ # <field>` to the owner controller as the download action, so the field
537
+ # must not redefine anything that controller already answers to. A
538
+ # field named `params` would make every action (the download's own
539
+ # `params[:id]` included) recurse; `head` would turn the download's
540
+ # `head 404` into a call to itself. Three groups:
541
+ # - the scaffold's actions;
542
+ # - every instance method and reader of Cybertrain::Controller,
543
+ # public or private (cybertrain/controller.rb);
544
+ # - the methods the generators write into ApplicationController
545
+ # (Templates.application_controller and the authentication block).
546
+ # Names ending in ? or ! are left out: a field name cannot have them.
547
+ # script/check-reserved-names fails when Controller or those templates
548
+ # gain a method this list lacks. The per-model helpers (set_<model>,
549
+ # <model>_params) are checked by attachment_action_clash?.
550
+ ATTACHMENT_RESERVED_ACTIONS = %w[
551
+ index show new new_action edit create update destroy
552
+ 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
555
+ run_action run_before_callbacks run_after_callbacks run_one
556
+ 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
562
+ ]
563
+
564
+ # Whether `field` as the name of the download action `def <field>` on
565
+ # the controller of `singular` would redefine one of its methods: the
566
+ # list above, or the scaffold's private set_<model> / <model>_params.
567
+ def self.attachment_action_clash?(field, singular)
568
+ ATTACHMENT_RESERVED_ACTIONS.include?(field) || field == "set_#{singular}" || field == "#{singular}_params"
569
+ end
570
+
571
+ # ["cover_key", "cover_filename", ...] for the attachment field `field`.
572
+ def self.attachment_column_names(field)
573
+ names = Array.new(0) { "" }
574
+ ATTACHMENT_COLUMNS.each { |col| names << "#{field}_#{col[0]}" }
575
+ names
576
+ end
577
+
578
+ # The schema DSL lines of those columns, as a create_table block writes
579
+ # them: `t.string "cover_key", null: false, default: "''"`.
580
+ def self.attachment_table_lines(field)
581
+ lines = Array.new(0) { "" }
582
+ ATTACHMENT_COLUMNS.each do |col|
583
+ lines << "t.#{col[1]} \"#{field}_#{col[0]}\", null: false, default: \"#{col[2]}\""
584
+ end
585
+ lines
586
+ end
587
+
250
588
  # ---- cybertrain generate scaffold --------------------------------
251
589
 
252
590
  def self.migration(res)
@@ -254,7 +592,7 @@ module Cybertrain
254
592
  buf << "class Create#{res.plural_class} < Cybertrain::Migration::Base\n"
255
593
  buf << " def change\n"
256
594
  buf << " create_table \"#{res.plural}\" do |t|\n"
257
- res.fields.each { |f| buf << " #{f.migration_line}\n" }
595
+ res.fields.each { |f| f.migration_lines.each { |line| buf << " #{line}\n" } }
258
596
  buf << " t.timestamps\n"
259
597
  buf << " end\n"
260
598
  buf << " end\n"
@@ -277,7 +615,17 @@ module Cybertrain
277
615
  s = res.singular
278
616
  p = res.plural
279
617
  human = humanize(s)
280
- permitted = res.fields.map { |f| ":#{f.column_name}" }.join(", ")
618
+ # An attachment is not a column and never goes through permit: the
619
+ # create and update actions hand it to `<field>_file=` as an
620
+ # UploadedFile (cli/attachment.rb), so a file can never be mass-assigned.
621
+ permit_list = Array.new(0) { "" }
622
+ res.fields.each { |f| permit_list << ":#{f.column_name}" unless f.attachment? }
623
+ permitted = permit_list.join(", ")
624
+ # A form whose only fields are files sends no `#{s}[...]` key at all
625
+ # when no file is chosen (the parser drops an empty file input), so
626
+ # `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"
281
629
  <<~RUBY
282
630
  class #{res.plural_class}Controller < ApplicationController
283
631
  before_action :set_#{s}, only: [:show, :edit, :update, :destroy]
@@ -336,7 +684,7 @@ module Cybertrain
336
684
  end
337
685
 
338
686
  def #{s}_params
339
- params.require(:#{s}).permit(#{permitted})
687
+ params.#{lookup}(:#{s}).permit(#{permitted})
340
688
  end
341
689
  end
342
690
  RUBY
@@ -352,7 +700,14 @@ module Cybertrain
352
700
  buf << " <th></th>\n </tr>\n </thead>\n <tbody>\n"
353
701
  buf << " <% @#{res.plural}.each do |#{s}| %>\n"
354
702
  buf << " <tr>\n"
355
- res.fields.each { |f| buf << " <td><%= #{s}.#{f.column_name} %></td>\n" }
703
+ res.fields.each do |f|
704
+ if f.attachment?
705
+ # A link to the file, not an <img>: a list of full-size images is heavy.
706
+ buf << " <td><% if #{s}.#{f.field_name}_attached? %><a href=\"<%= #{s}.#{f.field_name}_url %>\"><%= #{s}.#{f.field_name}_filename %></a><% end %></td>\n"
707
+ else
708
+ buf << " <td><%= #{s}.#{f.column_name} %></td>\n"
709
+ end
710
+ end
356
711
  buf << " <td><%= link_to \"Show\", #{s}_path(#{s}) %></td>\n"
357
712
  buf << " </tr>\n"
358
713
  buf << " <% end %>\n"
@@ -367,7 +722,11 @@ module Cybertrain
367
722
  buf = +""
368
723
  buf << "<h1>#{humanize(s)}</h1>\n\n"
369
724
  res.fields.each do |f|
370
- buf << "<p>\n <strong>#{f.label}:</strong>\n <%= @#{s}.#{f.column_name} %>\n</p>\n\n"
725
+ if f.attachment?
726
+ buf << attachment_show_paragraph(s, f, res.any)
727
+ else
728
+ buf << "<p>\n <strong>#{f.label}:</strong>\n <%= @#{s}.#{f.column_name} %>\n</p>\n\n"
729
+ end
371
730
  end
372
731
  buf << "<p>\n"
373
732
  buf << " <%= link_to \"Edit this #{words}\", edit_#{s}_path(@#{s}) %> |\n"
@@ -377,6 +736,22 @@ module Cybertrain
377
736
  buf
378
737
  end
379
738
 
739
+ # The show page's paragraph for an attachment field: the image itself
740
+ # for the raster-image default, a download link with --any.
741
+ def self.attachment_show_paragraph(s, f, any)
742
+ name = f.field_name
743
+ buf = +""
744
+ buf << "<p>\n <strong>#{f.label}:</strong>\n"
745
+ buf << " <% if @#{s}.#{name}_attached? %>\n"
746
+ if any
747
+ buf << " <a href=\"<%= @#{s}.#{name}_url %>\"><%= @#{s}.#{name}_filename %></a>\n"
748
+ else
749
+ buf << " <img src=\"<%= @#{s}.#{name}_url %>\" alt=\"<%= @#{s}.#{name}_filename %>\">\n"
750
+ end
751
+ buf << " <% end %>\n</p>\n\n"
752
+ buf
753
+ end
754
+
380
755
  def self.new_view(res)
381
756
  s = res.singular
382
757
  buf = +""
@@ -402,7 +777,8 @@ module Cybertrain
402
777
  s = res.singular
403
778
  buf = +""
404
779
  buf << "<%# locals: (#{s}:) %>\n"
405
- buf << "<%= form_with(model: #{s}) do |f| %>\n"
780
+ multipart = res.attachments?
781
+ buf << (multipart ? "<%= form_with(model: #{s}, multipart: true) do |f| %>\n" : "<%= form_with(model: #{s}) do |f| %>\n")
406
782
  buf << " <% if #{s}.errors.any? %>\n"
407
783
  buf << " <div id=\"error_explanation\">\n"
408
784
  buf << " <h2><%= pluralize(#{s}.errors.count, \"error\") %> prohibited this #{s.tr("_", " ")} from being saved:</h2>\n"
@@ -416,7 +792,12 @@ module Cybertrain
416
792
  res.fields.each do |f|
417
793
  buf << " <div class=\"field\">\n"
418
794
  buf << " <%= f.label :#{f.column_name} %>\n"
419
- buf << " <%= f.#{f.form_input} :#{f.column_name} %>\n"
795
+ if f.attachment?
796
+ accept = res.any ? "" : ", accept: \"#{ATTACHMENT_ACCEPT}\""
797
+ buf << " <%= f.file_field :#{f.field_name}#{accept} %>\n"
798
+ else
799
+ buf << " <%= f.#{f.form_input} :#{f.column_name} %>\n"
800
+ end
420
801
  buf << " </div>\n\n"
421
802
  end
422
803
  buf << " <div class=\"actions\">\n"