inline_forms 8.1.75 → 8.1.76

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.
Files changed (89) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -1
  3. data/README.rdoc +1 -1
  4. data/inline_forms.gemspec +0 -1
  5. data/lib/generators/USAGE +1 -1
  6. data/lib/generators/inline_forms_addto/USAGE +1 -1
  7. data/lib/generators/inline_forms_addto_generator.rb +30 -139
  8. data/lib/generators/inline_forms_attribute_list_editor.rb +211 -0
  9. data/lib/generators/inline_forms_attribute_overrides.rb +9 -0
  10. data/lib/generators/inline_forms_generator.rb +16 -35
  11. data/lib/inline_forms/gem_files.rb +20 -17
  12. data/lib/inline_forms/version.rb +1 -1
  13. metadata +3 -142
  14. data/.document +0 -5
  15. data/.forgejo/brakeman-engine.sh +0 -51
  16. data/.forgejo/brakeman.ignore +0 -211
  17. data/.forgejo/workflows/ci.yml +0 -74
  18. data/.forgejo/workflows/full-gate.yml +0 -104
  19. data/.gitignore +0 -39
  20. data/.rubocop.yml +0 -31
  21. data/.rubocop_todo.yml +0 -151
  22. data/.ruby-version +0 -1
  23. data/Gemfile +0 -28
  24. data/Rakefile +0 -103
  25. data/script/migrate_form_elements.rb +0 -62
  26. data/test/archived_form_elements_test.rb +0 -101
  27. data/test/attribute_list_test.rb +0 -165
  28. data/test/dummy/app/controllers/application_controller.rb +0 -32
  29. data/test/dummy/app/controllers/daily_reports_controller.rb +0 -4
  30. data/test/dummy/app/controllers/documents_controller.rb +0 -4
  31. data/test/dummy/app/controllers/dossiers_controller.rb +0 -4
  32. data/test/dummy/app/controllers/gizmos_controller.rb +0 -4
  33. data/test/dummy/app/controllers/machines_controller.rb +0 -4
  34. data/test/dummy/app/controllers/parts_controller.rb +0 -4
  35. data/test/dummy/app/controllers/stats_controller.rb +0 -10
  36. data/test/dummy/app/controllers/widgets_controller.rb +0 -4
  37. data/test/dummy/app/helpers/application_helper.rb +0 -13
  38. data/test/dummy/app/models/ability.rb +0 -15
  39. data/test/dummy/app/models/application_record.rb +0 -27
  40. data/test/dummy/app/models/daily_report.rb +0 -21
  41. data/test/dummy/app/models/document.rb +0 -33
  42. data/test/dummy/app/models/dossier.rb +0 -38
  43. data/test/dummy/app/models/gizmo.rb +0 -25
  44. data/test/dummy/app/models/kind.rb +0 -8
  45. data/test/dummy/app/models/machine.rb +0 -24
  46. data/test/dummy/app/models/part.rb +0 -17
  47. data/test/dummy/app/models/phase.rb +0 -9
  48. data/test/dummy/app/models/widget.rb +0 -40
  49. data/test/dummy/app/views/_gizmos_search.html.erb +0 -3
  50. data/test/dummy/app/views/stats/show.html.erb +0 -1
  51. data/test/dummy/config/application.rb +0 -49
  52. data/test/dummy/config/database.yml +0 -3
  53. data/test/dummy/config/environment.rb +0 -5
  54. data/test/dummy/config/initializers/inline_forms.rb +0 -6
  55. data/test/dummy/config/initializers/paper_trail_yaml_safe_load.rb +0 -28
  56. data/test/dummy/config/routes.rb +0 -51
  57. data/test/form_element_from_callee_test.rb +0 -73
  58. data/test/gem_package_modes_test.rb +0 -86
  59. data/test/inline_edit_polymorphic_path_test.rb +0 -81
  60. data/test/inline_forms_addto_generator_test.rb +0 -584
  61. data/test/inline_forms_generator_test.rb +0 -301
  62. data/test/integration/csp_nonce_test.rb +0 -50
  63. data/test/integration/dropdown_test.rb +0 -186
  64. data/test/integration/field_authorization_test.rb +0 -131
  65. data/test/integration/file_slots_test.rb +0 -665
  66. data/test/integration/html_refusal_test.rb +0 -152
  67. data/test/integration/inline_forms_crud_test.rb +0 -165
  68. data/test/integration/layout_title_test.rb +0 -56
  69. data/test/integration/legacy_elements_test.rb +0 -99
  70. data/test/integration/list_params_test.rb +0 -200
  71. data/test/integration/locale_test.rb +0 -234
  72. data/test/integration/model_top_bar_test.rb +0 -85
  73. data/test/integration/native_inputs_test.rb +0 -138
  74. data/test/integration/open_after_create_test.rb +0 -85
  75. data/test/integration/pending_migration_gate_test.rb +0 -75
  76. data/test/integration/presentation_escaping_test.rb +0 -80
  77. data/test/integration/revert_skipped_columns_test.rb +0 -59
  78. data/test/integration/schema_batch_pipeline_test.rb +0 -189
  79. data/test/integration/schema_edit_test.rb +0 -141
  80. data/test/integration/schema_preview_test.rb +0 -65
  81. data/test/integration/turbo_menu_test.rb +0 -60
  82. data/test/integration_test_helper.rb +0 -203
  83. data/test/plain_text_configuration_test.rb +0 -90
  84. data/test/schema_apply_test.rb +0 -73
  85. data/test/schema_intent_test.rb +0 -53
  86. data/test/schema_label_test.rb +0 -61
  87. data/test/tabs_test.rb +0 -98
  88. data/test/test_helper.rb +0 -10
  89. data/test/user_model_config_test.rb +0 -44
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d69ec6821783dbbfd063d6da1f553bd14db6340d5e32e0603d4e7b20ac460715
4
- data.tar.gz: a5c49b819eb32b2926ae306970747a6c1c42427246323bebd058282ff253b460
3
+ metadata.gz: eacea60e38ccfb9921c8418ce25e0568ba271ae9cfbf2eefe446bcc636a2fda6
4
+ data.tar.gz: 6dce6e955302de8c8cff17e5531bdfd30671225c535b0a85fabd9350f74e90a2
5
5
  SHA512:
6
- metadata.gz: 9235600ce6dc610d52de4d092b16cad9e7b795074d7659dab9f468bf59bf72950959541ed2f2d9e989e38c8613c7ee251c6336ef8f8f2a285d2435eeef6997be
7
- data.tar.gz: 9d058e992f4eec4ed8965406d1fbd526e241daa1ac7f4a83ba05e8ce23b479e20e1ab4dc4e9b4e1ed16d1aed356e49d72faca54cc9980764b47e29eb12b4184f
6
+ metadata.gz: 24ffd3ceab2f7a28e39f28b11b93a35567dc54537bcc716f551125cc5c93cf84949434008e875707dc3c94269cb5695bfd540901f7ad3b6a8d87d9865e628d2c
7
+ data.tar.gz: ad2c1281fb175ce689a4567c5c082cfaffaeb3543bb651d1694d9738199b1078eb608bd81aff1b1f6fa539720990af3c43491007885e1c80f2e7c142aec5bee3
data/CHANGELOG.md CHANGED
@@ -8,6 +8,30 @@ All notable changes to this project are documented in this file.
8
8
 
9
9
  - Known issues, parked (local note `stuff/2026-10-31-dropdown-rule-3-parked.md`) with dropdown order rule 3: `includes`, `group` or `select` in `inline_forms_list` make `dropdown` and `dropdown_with_other` raise while `/index` works, so 8.1.65's fix for a list order on a joined table holds only for `joins`, `left_joins` and `eager_load`; a has_many join gives duplicate options. Present since 8.1.60. No host's list scope has these today. Parked; not changed.
10
10
 
11
+ ## [8.1.76] - 2026-11-22
12
+
13
+ ### Fixed
14
+
15
+ - **`inline_forms_addto` no longer breaks a model's list.** Since 8.1.72 it could write a syntax error: no comma before a splat or a conditional row, none after a line with two rows, and one in the middle of `[ ... ].freeze`, a conditional row or a label with `]`. It also put a new row inside a last row of several lines (since before 8.1.72). The list is now found with Ruby's own parser (`InlineForms::AttributeListEditor`), the result is parsed again before it is written, and what cannot be placed leaves the list alone and prints the row to add by hand. The schema editor uses the same code.
16
+ - **`inline_forms_addto` writes precision and scale of a `decimal_field`,** 10,2 unless given as `{p,s}`, as `rails g inline_forms` does. Without them MySQL makes the column decimal(10,0) and drops the decimals. Columns that were added before are not changed.
17
+ - `rails g inline_forms` adds the model to `MODEL_TABS` when its name is only part of another one (`showcases` next to `form_element_showcases`).
18
+ - With `--allow-unknown`, the commented-out rows can be uncommented without adding a comma, and they and the commented-out columns are indented (RuboCop reported them). Columns in an addto migration are indented four spaces, not five.
19
+ - **Installer: an app pins a Ruby that is there.** `.ruby-version` gets the Ruby that runs the installer when 4.0.10 is not it and RVM does not have 4.0.10 (a warning says so when that Ruby is older).
20
+ - Installer: the Unicorn and Capistrano files no longer use figaro, which is not in the Gemfile, so Unicorn did not start. `DEPLOY_DIRECTORY` has to be in the environment.
21
+
22
+ ### Changed
23
+
24
+ - **Installer: no `.github/` in generated apps** (`rails new --skip-ci`): GitHub runs nothing. `bin/ci` and `config/ci.rb` stay.
25
+ - Installer: `bin/brakeman` no longer has `--ensure-latest`, which fails as soon as a newer Brakeman is released than the one in the app's lockfile.
26
+ - The gem packages only what an installed gem needs: `app`, `archived`, `lib`, `vendor/assets` and the documents. Tests, `script/`, `.forgejo/`, RuboCop and Ruby version files, `Gemfile` and `Rakefile` are left out.
27
+ - Installer: `brakeman`, `bundler-audit` and `rubocop-rails-omakase` are in the development group only. In the test group too, the generated Dockerfile put them in the production image.
28
+ - The example app's tests check that `bin/rubocop` starts, not that it finds nothing: a new RuboCop rule could make `inline_forms create --example` fail. The full gate runs `bin/ci` instead.
29
+
30
+ ### CI
31
+
32
+ - The full gate runs the generated app's `bin/ci`, and pins Brakeman to the version `.forgejo/brakeman.ignore` was made with.
33
+ - The engine scan skips only `config/credentials*` and `config/*.key`, not app code with such a name.
34
+
11
35
  ## [8.1.75] - 2026-11-22
12
36
 
13
37
  ### Removed
@@ -22,7 +46,7 @@ All notable changes to this project are documented in this file.
22
46
 
23
47
  ### Fixed
24
48
 
25
- - **Installer: the users/roles join table migration rolls back.** Its `down` said `drop_table roles_users`, without the colon, and raised `NoMethodError`. An existing app can correct that line in its own `db/migrate/*_inline_forms_create_join_table_*_role.rb`.
49
+ - **Installer: the users/roles join table migration rolls back.** Its `down` said `drop_table roles_users`, without the colon, and raised `NoMethodError`. An existing app can correct that line in its own `db/migrate/*_inline_forms_create_join_table_*_role.rb`. Look for it in other migrations too (`grep -rn 'drop_table [a-z]' db/migrate`): one copied from this template has to drop its own table, so do not just add the colon there.
26
50
 
27
51
  ### Tests
28
52
 
data/README.rdoc CHANGED
@@ -4,7 +4,7 @@ Inline Forms is almost a complete admin application. You can try it out easily.
4
4
 
5
5
  = Requirements
6
6
 
7
- * Ruby **>= 4.0** (generated apps pin **4.0.10** via +.ruby-version+)
7
+ * Ruby **>= 4.0** (generated apps pin **4.0.10** via +.ruby-version+, or the Ruby that runs the installer when 4.0.10 is not installed)
8
8
  * Rails **8.1.x**, at least **8.1.4.1** (+rails ~> 8.1+, +config.load_defaults 8.1+)
9
9
  * **validation_hints** **~> 8** (companion gem; same version line as +inline_forms+ / +inline_forms_installer+)
10
10
 
data/inline_forms.gemspec CHANGED
@@ -17,7 +17,6 @@ Gem::Specification.new do |s|
17
17
  s.required_ruby_version = ">= 4.0.0"
18
18
 
19
19
  s.files = InlineFormsGemFiles.gem_files(include_installer: false)
20
- s.test_files = s.files.grep(%r{^(test|spec|features)/})
21
20
  s.require_paths = [ "lib" ]
22
21
 
23
22
  s.add_dependency("validation_hints", ">= 8.1.4", "< 9.0")
data/lib/generators/USAGE CHANGED
@@ -21,7 +21,7 @@ This will create:
21
21
  [ :name, :text_field ],
22
22
  [ :description, :plain_text ],
23
23
  [ :yesno, :check_box ],
24
- [ :gender, :boolean_with_values ],
24
+ [ :gender, :boolean_with_values ]
25
25
  ]
26
26
  end
27
27
  end
@@ -29,7 +29,7 @@ Value-bearing form elements:
29
29
  Choice elements (dropdown_with_values, dropdown_with_integers,
30
30
  dropdown_with_values_with_stars, radio_button, check_box,
31
31
  scale_with_integers, scale_with_values) need a values hash as the 3rd row
32
- element. The generator inserts a placeholder `{ 1 => 'one', 2 => 'two' }`
32
+ element. The generator inserts a placeholder `{ 1 => "one", 2 => "two" }`
33
33
  and warns; edit it to your real values.
34
34
 
35
35
  Constraints and caveats:
@@ -1,6 +1,7 @@
1
1
  # -*- encoding : utf-8 -*-
2
2
  require "inline_forms"
3
3
  require_relative "inline_forms_attribute_overrides"
4
+ require_relative "inline_forms_attribute_list_editor"
4
5
 
5
6
  # == Usage
6
7
  #
@@ -40,11 +41,6 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
40
41
  # (shared with the schema GUI/preview).
41
42
  VALUE_BEARING_ELEMENTS = InlineForms::VALUE_BEARING_FORM_ELEMENTS
42
43
 
43
- # attribute_list rows whose form element (or name) marks the start of the
44
- # trailing "metadata" block. The smart-default placement inserts new rows
45
- # above this block instead of at the very end of the list.
46
- METADATA_ROW_NAMES = %w[created_at updated_at].freeze
47
-
48
44
  argument :attributes, type: :array, banner: "[name:form_element]..."
49
45
  class_option :allow_unknown, type: :boolean, default: false,
50
46
  desc: "Allow unknown field types (legacy behavior: comment generated lines instead of failing)."
@@ -124,8 +120,9 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
124
120
  @migration_lines << " add_column :#{table_name}, :#{columns[:data]}, :binary, **(connection.adapter_name.match?(/mysql|trilogy/i) ? { size: :long } : {})\n"
125
121
  @migration_lines << " add_column :#{table_name}, :#{columns[:content_type]}, :string\n"
126
122
  else
127
- commenter = attribute.attribute_type == :unknown ? "#" : " "
128
- @migration_lines << "#{commenter} add_column :#{table_name}, :#{attribute.name}, :#{attribute.column_type}\n"
123
+ commenter = attribute.attribute_type == :unknown ? "# " : ""
124
+ @migration_lines << " #{commenter}add_column :#{table_name}, :#{attribute.name}, " \
125
+ ":#{attribute.column_type}#{attribute.inline_forms_column_options}\n"
129
126
  end
130
127
  end
131
128
 
@@ -290,10 +287,8 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
290
287
  # generator-shaped list (e.g. only the inherited
291
288
  # `attr_writer :inline_forms_attribute_list` and no body).
292
289
  #
293
- # Row-aware, not regex-greedy: we locate the `[` after
294
- # `@inline_forms_attribute_list ||=` and bracket-depth scan to its
295
- # matching `]`, so the edit survives `].freeze`, trailing comments, and
296
- # any methods defined after the list. Placement honors `--after`/`--before`
290
+ # InlineForms::AttributeListEditor finds the list with Ruby's parser and
291
+ # places the row. Placement honors `--after`/`--before`
297
292
  # (by attribute name) and otherwise lands above the trailing metadata block
298
293
  # (`:info` rows / created_at / updated_at, and a `:header` directly above
299
294
  # them) instead of after it.
@@ -307,8 +302,10 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
307
302
  return
308
303
  end
309
304
 
310
- bounds = attribute_list_bounds(content)
311
- unless bounds
305
+ editor = attribute_list_editor(content, attribute)
306
+ return unless editor
307
+
308
+ unless editor.list?
312
309
  say_status :warn, "#{model_file_path}: no inline_forms_attribute_list found, appending a fresh method", :yellow
313
310
  body = <<~RUBY.gsub(/^(?=.)/, " ")
314
311
  def inline_forms_attribute_list
@@ -322,143 +319,37 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
322
319
  end
323
320
 
324
321
  warn_if_value_bearing!(attribute)
325
-
326
- open_idx, close_idx = bounds
327
- inner = content[(open_idx + 1)...close_idx]
328
- lines = inner.lines
329
- indent = detect_row_indent(lines)
330
-
331
- insert_at, note = insertion_index(lines, attribute)
332
-
333
- # A comma only when a row follows (RuboCop omakase wants none after the
334
- # last one).
335
- comma = lines.drop(insert_at).any? { |l| l.match?(/\A\s*\[/) } ? "," : ""
336
- new_line = "#{indent}#{attribute_row_literal(attribute)}#{comma}\n"
337
-
338
- # Keep the array valid: ensure the row we insert after ends with a comma.
339
- if insert_at.positive?
340
- prev = lines[insert_at - 1]
341
- lines[insert_at - 1] = with_trailing_comma(prev) if prev
342
- end
343
-
344
- lines.insert(insert_at, new_line)
345
- new_content = content[0..open_idx] + lines.join + content[close_idx..-1]
322
+ new_content, note = editor.insert(attribute_row_literal(attribute), **row_anchor(editor))
346
323
  File.write(path, new_content)
347
324
  say_status :insert, "#{model_file_path}: row :#{attribute.name}#{note}", :green
325
+ rescue InlineForms::AttributeListEditor::Unplaceable => e
326
+ row_not_added(attribute, e.message)
348
327
  end
349
328
 
350
- # `line` with a comma after its row, before a trailing comment if it has
351
- # one. Blank and comment lines, and rows that have their comma, unchanged.
352
- def with_trailing_comma(line)
353
- row = line.match(/\A(\s*)\[/)
354
- return line if line.match?(/\A\s*(#|\z)/)
355
-
356
- if row
357
- depth = 0
358
- ending = nil
359
- line.each_char.with_index do |char, index|
360
- depth += 1 if char == "["
361
- depth -= 1 if char == "]"
362
- if char == "]" && depth.zero?
363
- ending = index
364
- break
365
- end
366
- end
367
- end
368
- # Not a whole row on one line (the end of a longer one): its last `]`
369
- # outside a comment.
370
- ending ||= line.sub(/\s#.*/, "").rindex("]")
371
- return line if ending.nil? || line[(ending + 1)..].match?(/\A\s*,/)
372
-
373
- line.dup.insert(ending + 1, ",")
374
- end
375
-
376
- # Returns [open_bracket_index, close_bracket_index] for the
377
- # `@inline_forms_attribute_list ||= [ ... ]` array literal, or nil when the
378
- # model has no such list. Bracket-depth scan; nested `[ ]` (e.g. an
379
- # options_disabled array inside a choice row) balances correctly.
380
- def attribute_list_bounds(content)
381
- m = content.match(/@inline_forms_attribute_list\s*\|\|=\s*\[/)
382
- return nil unless m
383
-
384
- open_idx = m.end(0) - 1 # index of the '[' itself
385
- depth = 0
386
- i = open_idx
387
- while i < content.length
388
- case content[i]
389
- when "[" then depth += 1
390
- when "]"
391
- depth -= 1
392
- return [ open_idx, i ] if depth.zero?
393
- end
394
- i += 1
395
- end
329
+ def attribute_list_editor(content, attribute)
330
+ InlineForms::AttributeListEditor.new(content)
331
+ rescue InlineForms::AttributeListEditor::Unplaceable => e
332
+ row_not_added(attribute, e.message)
396
333
  nil
397
334
  end
398
335
 
399
- # Decide where the new row goes. Returns [line_index, status_note].
400
- def insertion_index(lines, _attribute)
401
- if (anchor = options[:after].to_s) != ""
402
- idx = row_line_index(lines, anchor)
403
- return [ idx + 1, " (after :#{anchor})" ] if idx
404
- say_status :warn, "#{model_file_path}: --after #{anchor} not found; using default placement", :yellow
405
- elsif (anchor = options[:before].to_s) != ""
406
- idx = row_line_index(lines, anchor)
407
- return [ idx, " (before :#{anchor})" ] if idx
408
- say_status :warn, "#{model_file_path}: --before #{anchor} not found; using default placement", :yellow
409
- end
410
-
411
- if (meta = metadata_start_index(lines))
412
- return [ meta, " (above metadata)" ]
413
- end
414
-
415
- [ last_row_index(lines) + 1, "" ]
416
- end
417
-
418
- def row_line_index(lines, name)
419
- lines.index { |l| row_name(l) == name.to_s }
420
- end
421
-
422
- def row_name(line)
423
- m = line.match(/\A\s*\[\s*:(\w+)\s*,/)
424
- m && m[1]
336
+ # Better no row than a model that does not load.
337
+ def row_not_added(attribute, reason)
338
+ say_status :error,
339
+ "#{model_file_path}: #{reason}; row not added. Add it by hand: #{attribute_row_literal(attribute)}",
340
+ :red
425
341
  end
426
342
 
427
- def row_element(line)
428
- m = line.match(/\A\s*\[\s*:\w+\s*,\s*:(\w+)/)
429
- m && m[1]
430
- end
431
-
432
- # Index of the first row that starts the trailing metadata block. If a
433
- # `:header` sits directly above that row, the header is treated as the
434
- # block start (so the new field lands above the header, not between it and
435
- # its info rows). nil when the list has no metadata block.
436
- def metadata_start_index(lines)
437
- first = nil
438
- lines.each_with_index do |l, i|
439
- if row_element(l) == "info" || METADATA_ROW_NAMES.include?(row_name(l))
440
- first = i
441
- break
442
- end
443
- end
444
- return nil unless first
343
+ # { after: name } or { before: name } when that row exists, else {}.
344
+ def row_anchor(editor)
345
+ key = %i[after before].find { |option| options[option].to_s != "" }
346
+ return {} unless key
445
347
 
446
- prev = first - 1
447
- (prev >= 0 && row_element(lines[prev]) == "header") ? prev : first
448
- end
449
-
450
- def last_row_index(lines)
451
- idx = nil
452
- lines.each_with_index { |l, i| idx = i if row_name(l) }
453
- idx || (lines.length - 1)
454
- end
348
+ name = options[key].to_s
349
+ return { key => name } if editor.row?(name)
455
350
 
456
- def detect_row_indent(lines)
457
- lines.each do |l|
458
- m = l.match(/\A(\s*)\[/)
459
- return m[1] if m
460
- end
461
- " " # 6 spaces, matching the create-time template
351
+ say_status :warn, "#{model_file_path}: --#{key} #{name} not found; using default placement", :yellow
352
+ {}
462
353
  end
463
354
 
464
355
  # `[ :name, :element ]`, or `[ :name, :element, { 1 => "one", 2 => "two" } ]`
@@ -0,0 +1,211 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+
5
+ module InlineForms
6
+ # Adds a row to the `@inline_forms_attribute_list ||= [ ... ]` literal in a
7
+ # model's source (used by `rails g inline_forms_addto`).
8
+ #
9
+ # The list is located with Prism, Ruby's own parser, so a row is whatever Ruby
10
+ # says is an element of the array: rows over several lines, several rows on
11
+ # one line, `.freeze`, conditional rows, splats, and brackets or `#` in a
12
+ # label or a comment are all just elements. The result is parsed again before
13
+ # it is returned; what cannot be placed raises Unplaceable and the caller
14
+ # leaves the file alone.
15
+ #
16
+ # Style of what is written (RuboCop omakase): a comma between rows, none after
17
+ # the last one.
18
+ class AttributeListEditor
19
+ class Unplaceable < StandardError; end
20
+
21
+ # attribute_list rows with these names, or with the :info element, start the
22
+ # trailing "metadata" block: new rows go above it by default.
23
+ METADATA_ROW_NAMES = %w[created_at updated_at].freeze
24
+ COMMENTED_ROW = /\A[ \t]*#[ \t]*\[[ \t]*:/
25
+
26
+ def initialize(source)
27
+ @source = source
28
+ @bytes = source.b
29
+ parsed = Prism.parse(source)
30
+ raise Unplaceable, "the file has a syntax error" if parsed.errors.any?
31
+
32
+ @array = find_array(parsed.value)
33
+ @elements = @array ? @array.elements : []
34
+ end
35
+
36
+ # false when the model has no such list, e.g. it inherits one.
37
+ def list?
38
+ !@array.nil?
39
+ end
40
+
41
+ def row?(name)
42
+ !index_of(name).nil?
43
+ end
44
+
45
+ # Returns [ new_source, note ]. +after+ / +before+ name an existing row; the
46
+ # caller checks with row? that it exists.
47
+ def insert(row, after: nil, before: nil)
48
+ raise Unplaceable, "there is no inline_forms_attribute_list" unless list?
49
+
50
+ edits, note = plan(row, after: after, before: before)
51
+ result = apply(edits)
52
+ verify!(result)
53
+ [ result, note ]
54
+ end
55
+
56
+ private
57
+
58
+ def plan(row, after:, before:)
59
+ return [ after_element(index_of(after), row), " (after :#{after})" ] if after
60
+ return [ before_element(index_of(before), row), " (before :#{before})" ] if before
61
+ return [ only_element(row), "" ] if @elements.empty?
62
+ if (metadata = metadata_start_index)
63
+ return [ before_element(metadata, row), " (above metadata)" ]
64
+ end
65
+
66
+ last_row = @elements.rindex { |element| row_symbols(element).any? } || @elements.size - 1
67
+ [ after_element(last_row, row), "" ]
68
+ end
69
+
70
+ # An edit is [ byte offset, text to insert, bytes to replace ].
71
+ def after_element(index, row)
72
+ element_end = @elements[index].location.end_offset
73
+ last = index == @elements.size - 1
74
+ following = last ? @array.closing_loc.start_offset : @elements[index + 1].location.start_offset
75
+ comma_end = comma_end_between(element_end, following)
76
+ position = comma_end || element_end
77
+ comma = comma_end ? "" : ","
78
+ separator = last ? "" : ","
79
+
80
+ line_end = @bytes.index("\n", position)
81
+ return [ [ position, "#{comma} #{row}#{separator}", 0 ] ] if line_end.nil? || line_end >= following
82
+
83
+ edits = comma_end ? [] : [ [ element_end, comma, 0 ] ]
84
+ position = line_end + 1
85
+ # Rows that are commented out below the last one keep the comma they have.
86
+ position = skip_commented_rows(position, following) if last
87
+ edits << [ position, "#{indent}#{row}#{separator}\n", 0 ]
88
+ end
89
+
90
+ def before_element(index, row)
91
+ start = @elements[index].location.start_offset
92
+ lead = line_lead(start)
93
+ return [ [ start - lead.bytesize, "#{lead}#{row},\n", 0 ] ] if lead
94
+
95
+ [ [ start, "#{row}, ", 0 ] ]
96
+ end
97
+
98
+ def only_element(row)
99
+ closing = @array.closing_loc.start_offset
100
+ lead = line_lead(closing)
101
+ return [ [ closing - lead.bytesize, "#{indent}#{row}\n", 0 ] ] if lead
102
+
103
+ opening_end = @array.opening_loc.end_offset
104
+ [ [ opening_end, "\n#{indent}#{row}\n#{base_indent}", closing - opening_end ] ]
105
+ end
106
+
107
+ def apply(edits)
108
+ result = @bytes.dup
109
+ edits.sort_by(&:first).reverse_each do |position, text, length|
110
+ result[position, length] = text.b
111
+ end
112
+ result.force_encoding(@source.encoding)
113
+ end
114
+
115
+ def verify!(result)
116
+ edited = self.class.new(result)
117
+ return if edited.send(:element_count) == @elements.size + 1
118
+
119
+ raise Unplaceable, "the row would not become one element of the list"
120
+ end
121
+
122
+ def element_count
123
+ @elements.size
124
+ end
125
+
126
+ def find_array(node)
127
+ queue = [ node ]
128
+ until queue.empty?
129
+ current = queue.shift
130
+ if current.is_a?(Prism::InstanceVariableOrWriteNode) && current.name == :@inline_forms_attribute_list
131
+ array = leftmost_array(current.value)
132
+ return array if array
133
+ end
134
+ queue.concat(current.compact_child_nodes)
135
+ end
136
+ nil
137
+ end
138
+
139
+ # The array literal in `[ ... ]`, `[ ... ].freeze` or `[ ... ] + MORE`.
140
+ def leftmost_array(node)
141
+ node = node.receiver while node.is_a?(Prism::CallNode)
142
+ node if node.is_a?(Prism::ArrayNode) && node.opening_loc&.slice == "["
143
+ end
144
+
145
+ # [ name, form element ] of a row as strings; empty for anything else.
146
+ def row_symbols(element)
147
+ array = leftmost_array(element)
148
+ return [] unless array
149
+
150
+ symbols = array.elements.first(2)
151
+ return [] unless symbols.first.is_a?(Prism::SymbolNode)
152
+
153
+ symbols.map { |node| node.unescaped if node.is_a?(Prism::SymbolNode) }
154
+ end
155
+
156
+ def index_of(name)
157
+ @elements.index { |element| row_symbols(element).first == name.to_s }
158
+ end
159
+
160
+ # A `:header` right above the first metadata row belongs to the block.
161
+ def metadata_start_index
162
+ first = @elements.index do |element|
163
+ name, form_element = row_symbols(element)
164
+ form_element == "info" || METADATA_ROW_NAMES.include?(name)
165
+ end
166
+ return nil unless first
167
+
168
+ first.positive? && row_symbols(@elements[first - 1])[1] == "header" ? first - 1 : first
169
+ end
170
+
171
+ # Between two elements there are only commas, whitespace and comments, but a
172
+ # comment may contain a comma: ask the lexer.
173
+ def comma_end_between(from, to)
174
+ @commas ||= Prism.lex(@source).value.filter_map do |token, _state|
175
+ token.location if token.type == :COMMA
176
+ end
177
+ @commas.find { |comma| comma.start_offset >= from && comma.start_offset < to }&.end_offset
178
+ end
179
+
180
+ def skip_commented_rows(position, limit)
181
+ while position < limit
182
+ line_end = @bytes.index("\n", position)
183
+ break unless line_end && line_end < limit && @bytes[position..line_end].match?(COMMENTED_ROW)
184
+
185
+ position = line_end + 1
186
+ end
187
+ position
188
+ end
189
+
190
+ # The whitespace before +offset+ when nothing else is on its line before it.
191
+ def line_lead(offset)
192
+ newline = offset.zero? ? nil : @bytes.rindex("\n", offset - 1)
193
+ line_start = newline ? newline + 1 : 0
194
+ lead = @bytes[line_start...offset]
195
+ lead if lead.match?(/\A[ \t]*\z/)
196
+ end
197
+
198
+ def indent
199
+ @elements.each do |element|
200
+ lead = line_lead(element.location.start_offset)
201
+ return lead if lead
202
+ end
203
+ "#{base_indent} "
204
+ end
205
+
206
+ def base_indent
207
+ newline = @bytes.rindex("\n", @array.opening_loc.start_offset)
208
+ @bytes[(newline ? newline + 1 : 0)..][/\A[ \t]*/]
209
+ end
210
+ end
211
+ end
@@ -105,6 +105,15 @@ Rails::Generators::GeneratedAttribute.class_eval do
105
105
  _no_model
106
106
  ].freeze unless const_defined?(:SPECIAL_GENERATOR_NAMES)
107
107
 
108
+ # Precision and scale of a decimal column, from `name:decimal_field{p,s}` or
109
+ # the 10,2 default. Without them MySQL makes it decimal(10,0) and drops the
110
+ # decimals. Empty for every other type.
111
+ def inline_forms_column_options
112
+ return "" unless column_type == :decimal
113
+
114
+ ", precision: #{attr_options[:precision] || 10}, scale: #{attr_options[:scale] || 2}"
115
+ end
116
+
108
117
  def migration?
109
118
  not ( column_type == :no_migration ||
110
119
  SPECIAL_GENERATOR_NAMES.include?(name))
@@ -127,17 +127,18 @@ module InlineForms
127
127
  @list_scopes << " inline_forms_search_on :#{attribute.type}\n"
128
128
  end
129
129
  if attribute.attribute?
130
- commenter = attribute.attribute_type == :unknown ? '#' : ' '
131
- rows << "#{commenter} [ :#{attribute.name}, :#{attribute.attribute_type} ]"
130
+ commenter = attribute.attribute_type == :unknown ? '# ' : ''
131
+ rows << " #{commenter}[ :#{attribute.name}, :#{attribute.attribute_type} ]"
132
132
  end
133
133
  end
134
134
  unless rows.empty?
135
- # No comma after the last row that is not commented out (RuboCop
136
- # omakase); inline_forms_addto adds it when it appends a row.
137
- last_row = rows.rindex { |row| !row.start_with?('#') }
138
- rows.each_with_index do |row, index|
139
- @inline_forms_attribute_list << row << (index == last_row ? "\n" : ",\n")
140
- end
135
+ # No comma after the last row (RuboCop omakase); inline_forms_addto adds
136
+ # it when it appends one. Commented-out rows at the end go above that
137
+ # last row, so that uncommenting one gives valid Ruby.
138
+ last_row = rows.rindex { |row| !row.lstrip.start_with?('#') }
139
+ last_row = rows.delete_at(last_row) if last_row
140
+ rows.each { |row| @inline_forms_attribute_list << row << ",\n" }
141
+ @inline_forms_attribute_list << last_row << "\n" if last_row
141
142
  @inline_forms_attribute_list = "\n" +
142
143
  " def inline_forms_attribute_list\n" +
143
144
  " @inline_forms_attribute_list ||= [\n" +
@@ -179,31 +180,9 @@ module InlineForms
179
180
  @columns << ' t.datetime :' + attribute.name + "_updated_at\n"
180
181
  else
181
182
  if attribute.migration?
182
- attribute.attribute_type == :unknown ? commenter = '#' : commenter = ' '
183
- # Render precision/scale for real :decimal columns. The override
184
- # in lib/generators/inline_forms_attribute_overrides.rb teaches
185
- # `Rails::Generators::GeneratedAttribute.parse` to extract
186
- # `{p,s}` off the type for :decimal_field (Rails' own parser
187
- # only honors `{…}` for a hardcoded list of built-in types
188
- # and otherwise glues the braces onto the type symbol).
189
- # Apply sensible defaults — precision: 10, scale: 2 — so a
190
- # bare `name:decimal_field` becomes a real decimal column
191
- # instead of the legacy varchar that 8.1.9 and earlier
192
- # emitted. Existing apps keep their varchar columns until
193
- # they migrate; only newly-generated tables get :decimal.
194
- column_opts = ""
195
- if attribute.column_type == :decimal
196
- precision = attribute.attr_options[:precision] || 10
197
- scale = attribute.attr_options[:scale] || 2
198
- column_opts = ", precision: #{precision}, scale: #{scale}"
199
- end
200
- @columns << commenter +
201
- ' t.' +
202
- attribute.column_type.to_s +
203
- " :" +
204
- attribute.name +
205
- column_opts +
206
- "\n"
183
+ commenter = attribute.attribute_type == :unknown ? '# ' : ''
184
+ @columns << " #{commenter}t.#{attribute.column_type} :#{attribute.name}" \
185
+ "#{attribute.inline_forms_column_options}\n"
207
186
  end
208
187
  end
209
188
  end
@@ -232,9 +211,11 @@ module InlineForms
232
211
 
233
212
  content = File.read(full_path)
234
213
  return unless content.match?(marker)
235
- return if content.include?(tab_token.rstrip)
214
+ # One of the words, not a substring: "showcases" is not there because
215
+ # "form_element_showcases" is. force: Thor skips on a substring too.
216
+ return if content[/MODEL_TABS = %w[\[(]([^\])]*)/, 1].to_s.split.include?(tab_token.rstrip)
236
217
 
237
- inject_into_file relative_path, tab_token, after: marker
218
+ inject_into_file relative_path, tab_token, after: marker, force: true
238
219
  end
239
220
 
240
221
  def generate_test