inline_forms 8.1.70 → 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 (92) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +81 -0
  3. data/README.rdoc +3 -3
  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/templates/add_columns_migration.erb +0 -2
  8. data/lib/generators/inline_forms_addto_generator.rb +40 -121
  9. data/lib/generators/inline_forms_attribute_list_editor.rb +211 -0
  10. data/lib/generators/inline_forms_attribute_overrides.rb +9 -0
  11. data/lib/generators/inline_forms_generator.rb +34 -41
  12. data/lib/generators/templates/migration.erb +0 -2
  13. data/lib/generators/templates/test.erb +1 -1
  14. data/lib/inline_forms/gem_files.rb +20 -17
  15. data/lib/inline_forms/version.rb +1 -1
  16. metadata +3 -142
  17. data/.document +0 -5
  18. data/.forgejo/brakeman-engine.sh +0 -51
  19. data/.forgejo/brakeman.ignore +0 -211
  20. data/.forgejo/workflows/ci.yml +0 -74
  21. data/.forgejo/workflows/full-gate.yml +0 -104
  22. data/.gitignore +0 -39
  23. data/.rubocop.yml +0 -31
  24. data/.rubocop_todo.yml +0 -151
  25. data/.ruby-version +0 -1
  26. data/Gemfile +0 -28
  27. data/Rakefile +0 -103
  28. data/script/migrate_form_elements.rb +0 -62
  29. data/test/archived_form_elements_test.rb +0 -101
  30. data/test/attribute_list_test.rb +0 -165
  31. data/test/dummy/app/controllers/application_controller.rb +0 -32
  32. data/test/dummy/app/controllers/daily_reports_controller.rb +0 -4
  33. data/test/dummy/app/controllers/documents_controller.rb +0 -4
  34. data/test/dummy/app/controllers/dossiers_controller.rb +0 -4
  35. data/test/dummy/app/controllers/gizmos_controller.rb +0 -4
  36. data/test/dummy/app/controllers/machines_controller.rb +0 -4
  37. data/test/dummy/app/controllers/parts_controller.rb +0 -4
  38. data/test/dummy/app/controllers/stats_controller.rb +0 -10
  39. data/test/dummy/app/controllers/widgets_controller.rb +0 -4
  40. data/test/dummy/app/helpers/application_helper.rb +0 -13
  41. data/test/dummy/app/models/ability.rb +0 -15
  42. data/test/dummy/app/models/application_record.rb +0 -27
  43. data/test/dummy/app/models/daily_report.rb +0 -21
  44. data/test/dummy/app/models/document.rb +0 -33
  45. data/test/dummy/app/models/dossier.rb +0 -38
  46. data/test/dummy/app/models/gizmo.rb +0 -25
  47. data/test/dummy/app/models/kind.rb +0 -8
  48. data/test/dummy/app/models/machine.rb +0 -24
  49. data/test/dummy/app/models/part.rb +0 -17
  50. data/test/dummy/app/models/phase.rb +0 -9
  51. data/test/dummy/app/models/widget.rb +0 -40
  52. data/test/dummy/app/views/_gizmos_search.html.erb +0 -3
  53. data/test/dummy/app/views/stats/show.html.erb +0 -1
  54. data/test/dummy/config/application.rb +0 -49
  55. data/test/dummy/config/database.yml +0 -3
  56. data/test/dummy/config/environment.rb +0 -5
  57. data/test/dummy/config/initializers/inline_forms.rb +0 -6
  58. data/test/dummy/config/initializers/paper_trail_yaml_safe_load.rb +0 -28
  59. data/test/dummy/config/routes.rb +0 -51
  60. data/test/form_element_from_callee_test.rb +0 -73
  61. data/test/gem_package_modes_test.rb +0 -86
  62. data/test/inline_edit_polymorphic_path_test.rb +0 -81
  63. data/test/inline_forms_addto_generator_test.rb +0 -518
  64. data/test/inline_forms_generator_test.rb +0 -261
  65. data/test/integration/csp_nonce_test.rb +0 -50
  66. data/test/integration/dropdown_test.rb +0 -186
  67. data/test/integration/field_authorization_test.rb +0 -131
  68. data/test/integration/file_slots_test.rb +0 -665
  69. data/test/integration/html_refusal_test.rb +0 -152
  70. data/test/integration/inline_forms_crud_test.rb +0 -165
  71. data/test/integration/layout_title_test.rb +0 -56
  72. data/test/integration/legacy_elements_test.rb +0 -99
  73. data/test/integration/list_params_test.rb +0 -200
  74. data/test/integration/locale_test.rb +0 -234
  75. data/test/integration/model_top_bar_test.rb +0 -85
  76. data/test/integration/native_inputs_test.rb +0 -138
  77. data/test/integration/open_after_create_test.rb +0 -85
  78. data/test/integration/pending_migration_gate_test.rb +0 -75
  79. data/test/integration/presentation_escaping_test.rb +0 -80
  80. data/test/integration/revert_skipped_columns_test.rb +0 -59
  81. data/test/integration/schema_batch_pipeline_test.rb +0 -189
  82. data/test/integration/schema_edit_test.rb +0 -141
  83. data/test/integration/schema_preview_test.rb +0 -65
  84. data/test/integration/turbo_menu_test.rb +0 -60
  85. data/test/integration_test_helper.rb +0 -203
  86. data/test/plain_text_configuration_test.rb +0 -90
  87. data/test/schema_apply_test.rb +0 -73
  88. data/test/schema_intent_test.rb +0 -53
  89. data/test/schema_label_test.rb +0 -61
  90. data/test/tabs_test.rb +0 -98
  91. data/test/test_helper.rb +0 -10
  92. data/test/user_model_config_test.rb +0 -44
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bba553f79844842a8f729c901f5b80e7e9648d5d3aa87f24ac27b639d912e1a6
4
- data.tar.gz: 6ebc4014b08c59dc54ac2477a911fe52ce5dbec418eee026746986fe472ea295
3
+ metadata.gz: eacea60e38ccfb9921c8418ce25e0568ba271ae9cfbf2eefe446bcc636a2fda6
4
+ data.tar.gz: 6dce6e955302de8c8cff17e5531bdfd30671225c535b0a85fabd9350f74e90a2
5
5
  SHA512:
6
- metadata.gz: 65785f30dad13fe689f34c0470542ac68472c084a40aea628a7855cd9f38a517bede9e2443f05143253531f540d890145eb3ffbce9ab6a30be7836feb6992ca1
7
- data.tar.gz: 4eb53f8cf94cfedbc2fcec376e74522b002f8093dda8beee33db4a4298f12526a61f1dd465e541163df5c0ad36917f42007ee3d43c05dc301d798847fd5d10dc
6
+ metadata.gz: 24ffd3ceab2f7a28e39f28b11b93a35567dc54537bcc716f551125cc5c93cf84949434008e875707dc3c94269cb5695bfd540901f7ad3b6a8d87d9865e628d2c
7
+ data.tar.gz: ad2c1281fb175ce689a4567c5c082cfaffaeb3543bb651d1694d9738199b1078eb608bd81aff1b1f6fa539720990af3c43491007885e1c80f2e7c142aec5bee3
data/CHANGELOG.md CHANGED
@@ -8,6 +8,87 @@ 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
+
35
+ ## [8.1.75] - 2026-11-22
36
+
37
+ ### Removed
38
+
39
+ - **Installer: no importmap in generated apps.** `importmap-rails`, and 8.1.73's `bin/importmap` and `config/importmap.rb`, are gone, and `rails new` runs with `--skip-javascript`, so `bin/ci` has no importmap audit. Nothing used it (JavaScript comes from gems through Sprockets), and `bin/importmap pin` downloads npm packages. Existing apps are not changed.
40
+
41
+ ### Tests
42
+
43
+ - The example app checks that importmap is not there, instead of running its audit.
44
+
45
+ ## [8.1.74] - 2026-11-22
46
+
47
+ ### Fixed
48
+
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.
50
+
51
+ ### Tests
52
+
53
+ - The example app rolls that migration back and runs it again (`example_app_roles_join_table_rollback_test.rb`).
54
+
55
+ ## [8.1.73] - 2026-11-22
56
+
57
+ ### Fixed
58
+
59
+ - **Installer: generated apps have `bin/importmap`** and a `config/importmap.rb` without pins. `bin/ci` runs `bin/importmap audit`, which failed because the file was missing; the app's JavaScript still comes from Sprockets. Existing apps are not changed.
60
+
61
+ ### Tests
62
+
63
+ - The example app runs `bin/importmap audit`.
64
+
65
+ ## [8.1.72] - 2026-11-22
66
+
67
+ ### Changed
68
+
69
+ - **Installer: generated apps have `rubocop-rails-omakase`** (development and test groups), the gem behind `bin/rubocop`, which `bin/ci` runs. The generated app had 335 offenses (all style); it now has none. Existing apps are not changed.
70
+ - **Generators write RuboCop's style:** double quotes and new hash syntax, no trailing spaces, no blank line at the start or end of a class, and no comma after the last `inline_forms_attribute_list` row. `inline_forms_addto` adds that comma when it appends a row, also before a trailing comment. Lists with the comma keep working, as does `MODEL_TABS = %w( )`, which is now written as `%w[ ]`. Re-running `inline_forms_addto` recognises the `:dependent => :destroy` line it wrote before.
71
+ - The installer runs `bin/rubocop -a` on the files Devise's and PaperTrail's generators write (`config/initializers/devise.rb` and the versions migrations).
72
+
73
+ ### Fixed
74
+
75
+ - The installer's Devise mailer settings are indented and on their own lines in `config/environments/*.rb`; in development.rb the first line was glued to Rails' last comment.
76
+
77
+ ### Tests
78
+
79
+ - The example app's suite runs `bin/rubocop` on the whole app.
80
+ - Generator tests for the style of the model and migration, lists with and without the last comma, and the pre-8.1.72 `MODEL_TABS` and `has_many` lines.
81
+
82
+ ## [8.1.71] - 2026-11-22
83
+
84
+ ### Fixed
85
+
86
+ - **Installer: generated apps have `brakeman` and `bundler-audit`** (development and test groups, `require: false`). `rails new` writes `bin/brakeman` and `bin/bundler-audit`, and `bin/ci` runs them, but the installer's own Gemfile left the gems out, so both failed. Existing apps are not changed.
87
+
88
+ ### Tests
89
+
90
+ - The example app runs both binstubs (`example_app_security_tools_test.rb`).
91
+
11
92
  ## [8.1.70] - 2026-11-22
12
93
 
13
94
  ### Changed
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
 
@@ -279,8 +279,8 @@ LONGBLOB column plus a content-type column). Declare the slot on the model:
279
279
 
280
280
  # routes.rb
281
281
  resources :clients do
282
- post 'revert', :on => :member
283
- get 'list_versions', :on => :member
282
+ post "revert", on: :member
283
+ get "list_versions", on: :member
284
284
  InlineForms.file_routes(self)
285
285
  end
286
286
  InlineForms.draw_file_trash_routes(self) # global trash page, /file_trash
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,7 +1,5 @@
1
1
  class <%= migration_class_name %> < ActiveRecord::Migration[8.1]
2
-
3
2
  def change
4
3
  <%= @migration_lines -%>
5
4
  end
6
-
7
5
  end
@@ -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
 
@@ -157,7 +154,7 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
157
154
  when :has_many
158
155
  inject_class_line!(" has_many :#{attribute.name}\n")
159
156
  when :has_many_destroy
160
- inject_class_line!(" has_many :#{attribute.name}, :dependent => :destroy\n")
157
+ inject_class_line!(" has_many :#{attribute.name}, dependent: :destroy\n")
161
158
  when :has_one
162
159
  inject_class_line!(" has_one :#{attribute.name}\n")
163
160
  when :habtm, :has_and_belongs_to_many, :check_list
@@ -277,7 +274,8 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
277
274
  def inject_class_line!(line)
278
275
  content = File.read(File.join(destination_root, model_file_path))
279
276
  probe = line.rstrip
280
- if content.include?(probe)
277
+ # `:dependent => :destroy` is what this generator wrote before 8.1.72.
278
+ if content.gsub(":dependent => ", "dependent: ").include?(probe)
281
279
  say_status :identical, "#{model_file_path}: #{probe.strip}", :blue
282
280
  return
283
281
  end
@@ -289,10 +287,8 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
289
287
  # generator-shaped list (e.g. only the inherited
290
288
  # `attr_writer :inline_forms_attribute_list` and no body).
291
289
  #
292
- # Row-aware, not regex-greedy: we locate the `[` after
293
- # `@inline_forms_attribute_list ||=` and bracket-depth scan to its
294
- # matching `]`, so the edit survives `].freeze`, trailing comments, and
295
- # 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`
296
292
  # (by attribute name) and otherwise lands above the trailing metadata block
297
293
  # (`:info` rows / created_at / updated_at, and a `:header` directly above
298
294
  # them) instead of after it.
@@ -306,14 +302,15 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
306
302
  return
307
303
  end
308
304
 
309
- bounds = attribute_list_bounds(content)
310
- unless bounds
311
- say_status :warn, "#{model_file_path}: no inline_forms_attribute_list found, appending a fresh method", :yellow
312
- body = <<~RUBY.gsub(/^/, " ")
305
+ editor = attribute_list_editor(content, attribute)
306
+ return unless editor
313
307
 
308
+ unless editor.list?
309
+ say_status :warn, "#{model_file_path}: no inline_forms_attribute_list found, appending a fresh method", :yellow
310
+ body = <<~RUBY.gsub(/^(?=.)/, " ")
314
311
  def inline_forms_attribute_list
315
312
  @inline_forms_attribute_list ||= [
316
- #{attribute_row_literal(attribute)},
313
+ #{attribute_row_literal(attribute)}
317
314
  ]
318
315
  end
319
316
  RUBY
@@ -322,123 +319,45 @@ 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
- new_line = "#{indent}#{attribute_row_literal(attribute)},\n"
331
-
332
- insert_at, note = insertion_index(lines, attribute)
333
-
334
- # Keep the array valid: ensure the row we insert after ends with a comma.
335
- if insert_at.positive?
336
- prev = lines[insert_at - 1]
337
- if prev && prev.match?(/\S/) && !prev.match?(/,\s*\z/)
338
- lines[insert_at - 1] = prev.sub(/(\S)(\s*)\z/, "\\1,\\2")
339
- end
340
- end
341
-
342
- lines.insert(insert_at, new_line)
343
- 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))
344
323
  File.write(path, new_content)
345
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)
346
327
  end
347
328
 
348
- # Returns [open_bracket_index, close_bracket_index] for the
349
- # `@inline_forms_attribute_list ||= [ ... ]` array literal, or nil when the
350
- # model has no such list. Bracket-depth scan; nested `[ ]` (e.g. an
351
- # options_disabled array inside a choice row) balances correctly.
352
- def attribute_list_bounds(content)
353
- m = content.match(/@inline_forms_attribute_list\s*\|\|=\s*\[/)
354
- return nil unless m
355
-
356
- open_idx = m.end(0) - 1 # index of the '[' itself
357
- depth = 0
358
- i = open_idx
359
- while i < content.length
360
- case content[i]
361
- when "[" then depth += 1
362
- when "]"
363
- depth -= 1
364
- return [ open_idx, i ] if depth.zero?
365
- end
366
- i += 1
367
- 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)
368
333
  nil
369
334
  end
370
335
 
371
- # Decide where the new row goes. Returns [line_index, status_note].
372
- def insertion_index(lines, _attribute)
373
- if (anchor = options[:after].to_s) != ""
374
- idx = row_line_index(lines, anchor)
375
- return [ idx + 1, " (after :#{anchor})" ] if idx
376
- say_status :warn, "#{model_file_path}: --after #{anchor} not found; using default placement", :yellow
377
- elsif (anchor = options[:before].to_s) != ""
378
- idx = row_line_index(lines, anchor)
379
- return [ idx, " (before :#{anchor})" ] if idx
380
- say_status :warn, "#{model_file_path}: --before #{anchor} not found; using default placement", :yellow
381
- end
382
-
383
- if (meta = metadata_start_index(lines))
384
- return [ meta, " (above metadata)" ]
385
- end
386
-
387
- [ last_row_index(lines) + 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
388
341
  end
389
342
 
390
- def row_line_index(lines, name)
391
- lines.index { |l| row_name(l) == name.to_s }
392
- end
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
393
347
 
394
- def row_name(line)
395
- m = line.match(/\A\s*\[\s*:(\w+)\s*,/)
396
- m && m[1]
397
- end
348
+ name = options[key].to_s
349
+ return { key => name } if editor.row?(name)
398
350
 
399
- def row_element(line)
400
- m = line.match(/\A\s*\[\s*:\w+\s*,\s*:(\w+)/)
401
- m && m[1]
402
- end
403
-
404
- # Index of the first row that starts the trailing metadata block. If a
405
- # `:header` sits directly above that row, the header is treated as the
406
- # block start (so the new field lands above the header, not between it and
407
- # its info rows). nil when the list has no metadata block.
408
- def metadata_start_index(lines)
409
- first = nil
410
- lines.each_with_index do |l, i|
411
- if row_element(l) == "info" || METADATA_ROW_NAMES.include?(row_name(l))
412
- first = i
413
- break
414
- end
415
- end
416
- return nil unless first
417
-
418
- prev = first - 1
419
- (prev >= 0 && row_element(lines[prev]) == "header") ? prev : first
420
- end
421
-
422
- def last_row_index(lines)
423
- idx = nil
424
- lines.each_with_index { |l, i| idx = i if row_name(l) }
425
- idx || (lines.length - 1)
426
- end
427
-
428
- def detect_row_indent(lines)
429
- lines.each do |l|
430
- m = l.match(/\A(\s*)\[/)
431
- return m[1] if m
432
- end
433
- " " # 6 spaces, matching the create-time template
351
+ say_status :warn, "#{model_file_path}: --#{key} #{name} not found; using default placement", :yellow
352
+ {}
434
353
  end
435
354
 
436
- # `[ :name, :element ]`, or `[ :name, :element, { 1 => 'one', 2 => 'two' } ]`
355
+ # `[ :name, :element ]`, or `[ :name, :element, { 1 => "one", 2 => "two" } ]`
437
356
  # for value-bearing choice elements (a placeholder the user then edits).
438
357
  def attribute_row_literal(attribute)
439
358
  el = attribute.attribute_type
440
359
  if VALUE_BEARING_ELEMENTS.include?(el)
441
- "[ :#{attribute.name}, :#{el}, { 1 => 'one', 2 => 'two' } ]"
360
+ "[ :#{attribute.name}, :#{el}, { 1 => \"one\", 2 => \"two\" } ]"
442
361
  else
443
362
  "[ :#{attribute.name}, :#{el} ]"
444
363
  end
@@ -449,7 +368,7 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
449
368
 
450
369
  say_status :warn,
451
370
  "#{model_file_path}: :#{attribute.name} is a #{attribute.attribute_type}; " \
452
- "edit the placeholder values hash { 1 => 'one', ... }",
371
+ "edit the placeholder values hash { 1 => \"one\", ... }",
453
372
  :yellow
454
373
  end
455
374
 
@@ -471,7 +390,7 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
471
390
  / def _presentation\b.*?\n end\n/m,
472
391
  new_method
473
392
  else
474
- inject_into_class model_file_path, model_class_name, "\n#{new_method}"
393
+ inject_into_class model_file_path, model_class_name, "#{new_method}\n"
475
394
  end
476
395
  when "_list_order", "_order"
477
396
  col = attribute.type
@@ -487,7 +406,7 @@ class InlineFormsAddtoGenerator < Rails::Generators::NamedBase
487
406
  if content.match?(/def <=>\(other\)/)
488
407
  gsub_file model_file_path, / def <=>\(other\).*?\n end\n/m, new_spaceship
489
408
  else
490
- inject_into_class model_file_path, model_class_name, "\n#{new_spaceship}"
409
+ inject_into_class model_file_path, model_class_name, "#{new_spaceship}\n"
491
410
  end
492
411
  when "_list_search"
493
412
  col = attribute.type
@@ -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))