rubocop-dev_doc 0.15.0 → 0.17.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: cad88b36f561dcd41b75c42c242bf3af1877081c6df2c43ffeeaf3edbdb9e712
4
- data.tar.gz: ae68d462103ffb1bc792bf4cb7bc65e20ecd8eb773a7b729f0194b070833b487
3
+ metadata.gz: 11175a594b0adb68ca20c3e2ff0ef414d1136d55152cd010a8d95ee26601a759
4
+ data.tar.gz: 460f211f62e554bead8cd267a4c3e918159eccff748d2d03f0f06b56454d025e
5
5
  SHA512:
6
- metadata.gz: 5a74d067f5e2f0e7ca71f6457a590db627cde1bfe30349bccedaa363b3f7d8a08dc503eb5e301d7056434a03c600fbd85e716f95054d74a98a74b02923e17bba
7
- data.tar.gz: 8439d5bb064c8d5211213f2912a6815cc3b4fb26db881f7f0bcd844a7b00ff11bcb457ab4a754c4144758e4dd203263afb51e81b13e6c3c862e7b4ae496b3b5d
6
+ metadata.gz: 5b5a9ae0aed54ff1979d4deb8313ef53e0e8b3d831e9d3bbdabaf9c4d9c3897acd7486054cbd012222453c9e6dbcd0054821ea83ddac71c1231bc51d7be6072e
7
+ data.tar.gz: e6acacc3e7f65769104c90d5043a08c6385983ab6c9f38db8088ff30193044ac1cd6e14b365c1cbf521de52d445b84e9c4312f75e2dcb6ab93370077a8134bed
data/config/default.yml CHANGED
@@ -188,6 +188,17 @@ DevDoc/Rails/NoTransactionInController:
188
188
  Include:
189
189
  - "app/controllers/**/*.rb"
190
190
 
191
+ # Same placement rule in an assignment costume: `collection_ids=` on a
192
+ # persisted record writes the join table immediately (no save, no
193
+ # validations), so a controller-side ids write either bypasses the guards the
194
+ # operation's form object/model enforces on its other write paths, or mutates
195
+ # the association even when the surrounding operation fails afterwards.
196
+ DevDoc/Rails/NoCollectionIdsWriterInController:
197
+ Description: "Association `*_ids=` writers in controllers persist join rows immediately on a persisted record, bypassing validations; move the write into the model method or form object that owns the operation's validations."
198
+ Enabled: true
199
+ Include:
200
+ - "app/controllers/**/*.rb"
201
+
191
202
  DevDoc/Rails/EnumMustBeSymbolized:
192
203
  Description: "Declare enums with `enum_symbolize :foo, { … }` instead of a bare `enum`, so the attribute type is set before the enum and the reader returns a symbol."
193
204
  Enabled: true
@@ -392,6 +403,18 @@ DevDoc/Rails/ApplicationRecordTransaction:
392
403
  Exclude:
393
404
  - "app/models/**/*.rb"
394
405
 
406
+ DevDoc/Rails/ApplicationModelBase:
407
+ Description: "Inherit the app's ApplicationModel root instead of including ActiveModel::Model directly (three-way rule, backend/03_model.md item 9)."
408
+ # Disabled by default: requires the project to have an ApplicationModel root
409
+ # over glib-web's Glib::Model. Enable per project, scoped to app/models; the
410
+ # root itself and any engine-side base need excluding where they legitimately
411
+ # carry the include.
412
+ Enabled: false
413
+ Include:
414
+ - "app/models/**/*.rb"
415
+ Exclude:
416
+ - "app/models/application_model.rb"
417
+
395
418
  DevDoc/Style/AvoidOptionsHash:
396
419
  Description: "Use keyword arguments instead of `**options` — typos raise `ArgumentError`; options hashes swallow them silently."
397
420
  Enabled: true
@@ -0,0 +1,138 @@
1
+ require 'pathname'
2
+
3
+ module DevDoc
4
+ module Test
5
+ module Lints
6
+ # Runtime check: every CLASS defined by a file under `app/models/`
7
+ # (excluding `concerns/`) must descend from one of the project's domain
8
+ # base classes. Runs with the app loaded, so real ancestry is checked —
9
+ # intermediate family bases and indirect inheritance resolve correctly,
10
+ # which is exactly what a per-file static cop cannot do.
11
+ #
12
+ # Wrapped by the Minitest module `DomainClassBase` below — see that
13
+ # module for the rationale.
14
+ class DomainClassBaseChecker
15
+ # The three-way rule (best_practices/backend/en/03_model.md item 9):
16
+ # persisted -> ApplicationRecord; table-less but form-backed ->
17
+ # ApplicationModel; plain domain logic -> PlainModel.
18
+ DEFAULT_BASE_CLASS_NAMES = %w[ApplicationRecord ApplicationModel PlainModel].freeze
19
+
20
+ def initialize(project_root, base_class_names: DEFAULT_BASE_CLASS_NAMES, allowed_paths: [])
21
+ @project_root = Pathname(project_root)
22
+ @base_class_names = base_class_names
23
+ @allowed_paths = allowed_paths
24
+ end
25
+
26
+ # Returns an Array<String> of offender descriptions, or `[]` when
27
+ # every model class descends from an allowed base. Modules are skipped:
28
+ # the three-way rule classifies CLASSES — namespaces, function-bag
29
+ # modules, and concerns carry no instance state to classify.
30
+ def offenders
31
+ bases = @base_class_names.map(&:constantize)
32
+
33
+ model_files.filter_map do |path|
34
+ constant = constant_for(path)
35
+ next if constant.nil? # module or namespace-only file
36
+ next if bases.any? { |base| constant <= base }
37
+
38
+ " #{relative(path)}: #{constant.name} < #{constant.superclass.name} — #{hint_for(constant)}"
39
+ end
40
+ end
41
+
42
+ private
43
+
44
+ def model_files
45
+ Dir.glob(@project_root.join('app/models/**/*.rb')).reject do |path|
46
+ relative = relative(path)
47
+ relative.start_with?('app/models/concerns/') ||
48
+ @allowed_paths.any? { |allowed| relative.start_with?(allowed) }
49
+ end
50
+ end
51
+
52
+ # Zeitwerk guarantees the file defines the constant its path names, so
53
+ # deriving it from the path (rather than parsing the source) is exact,
54
+ # and nested helper classes (e.g. error classes inside a model) are
55
+ # never enumerated.
56
+ def constant_for(path)
57
+ name = relative(path).delete_prefix('app/models/').delete_suffix('.rb').camelize
58
+ constant = name.constantize
59
+ constant.is_a?(Class) ? constant : nil
60
+ end
61
+
62
+ def hint_for(constant)
63
+ if constant.include?(ActiveModel::Model)
64
+ 'it includes ActiveModel::Model, so inherit ApplicationModel instead'
65
+ else
66
+ 'inherit PlainModel (or ApplicationRecord/ApplicationModel if it persists or backs a form)'
67
+ end
68
+ end
69
+
70
+ def relative(path)
71
+ Pathname(path).relative_path_from(@project_root).to_s
72
+ end
73
+ end
74
+
75
+ # Domain-class base tripwire: every class under `app/models/` must be one
76
+ # of the project's three kinds — persisted (ApplicationRecord),
77
+ # form-backed (ApplicationModel), or plain domain logic (PlainModel).
78
+ #
79
+ # ## Rationale
80
+ # The three-way rule (backend/03_model.md item 9) makes the author
81
+ # classify each domain class at creation time; the base's docstring then
82
+ # states the contract that kind carries. Static analysis cannot enforce
83
+ # totality — RuboCop sees one file at a time, so it cannot resolve
84
+ # whether `class Foo < SomeFamilyBase` ultimately reaches an allowed
85
+ # base. This lint checks real ancestry with the app loaded, so
86
+ # intermediate bases resolve and the rule is enforced literally.
87
+ # `Rails/ApplicationRecord` and `DevDoc/Rails/ApplicationModelBase`
88
+ # remain useful beside it for editor-time feedback on the two common
89
+ # direct mistakes.
90
+ #
91
+ # NOTE: Limitations:
92
+ # - Only classes whose files live under `app/models/` are checked; a
93
+ # domain class parked elsewhere is invisible (placement itself is the
94
+ # orchestration taxonomy's reviewer-owned residual).
95
+ # - Modules are skipped by design (namespaces, function-bag modules,
96
+ # concerns) — the rule classifies classes.
97
+ #
98
+ # ## Usage
99
+ # Include this module in a Minitest test class (Rails test env) in a
100
+ # project whose three bases exist. Override the constants on the test
101
+ # class to rename bases or exempt a sanctioned file:
102
+ #
103
+ # class DomainClassBaseTest < ActiveSupport::TestCase
104
+ # include DevDoc::Test::Lints::DomainClassBase
105
+ # # DOMAIN_BASE_CLASS_NAMES = %w[ApplicationRecord ApplicationModel PlainModel].freeze
106
+ # # ALLOWED_DOMAIN_CLASS_PATHS = %w[app/models/legacy/].freeze
107
+ # end
108
+ module DomainClassBase
109
+ # Defaults. Per-project override: redefine the constants on the test
110
+ # class that includes this module.
111
+ DOMAIN_BASE_CLASS_NAMES = DomainClassBaseChecker::DEFAULT_BASE_CLASS_NAMES
112
+ ALLOWED_DOMAIN_CLASS_PATHS = [].freeze
113
+
114
+ def test_every_model_class_descends_from_a_domain_base
115
+ offenders = DomainClassBaseChecker.new(
116
+ Rails.root,
117
+ base_class_names: self.class::DOMAIN_BASE_CLASS_NAMES,
118
+ allowed_paths: self.class::ALLOWED_DOMAIN_CLASS_PATHS
119
+ ).offenders
120
+
121
+ assert offenders.empty?, domain_class_base_message(offenders)
122
+ end
123
+
124
+ private
125
+
126
+ def domain_class_base_message(offenders)
127
+ "Classes under app/models must descend from one of " \
128
+ "#{self.class::DOMAIN_BASE_CLASS_NAMES.join(' / ')} — the three-way rule " \
129
+ "(backend/03_model.md item 9): persisted -> ApplicationRecord, form-backed " \
130
+ "-> ApplicationModel, plain domain logic -> PlainModel. If a class is a " \
131
+ "sanctioned exception, add its path to ALLOWED_DOMAIN_CLASS_PATHS on the " \
132
+ "including test class with a comment.\n\n" \
133
+ "Offenders:\n#{offenders.join("\n")}"
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -2,13 +2,18 @@ module RuboCop
2
2
  module Cop
3
3
  module DevDoc
4
4
  module Auth
5
- # The adjacent-justification contract shared by the auth "flag and make
6
- # the developer state the mechanism" cops: an offense is silenced by a
7
- # comment containing the cop's marker phrase either on the flagged
8
- # node's own line (trailing) or in the contiguous comment block ending
9
- # on the line directly above it. Adjacency is the point a marker
10
- # elsewhere in the file justifies nothing. Host cops must provide
11
- # `justification_marker`.
5
+ # The adjacent-justification contract shared by the "flag and make the
6
+ # developer state the mechanism" cops (the auth family, and
7
+ # `DevDoc/Migration/AvoidNonNull`'s column-kind markers): an offense is
8
+ # silenced by a comment containing the cop's marker either on the
9
+ # flagged node's own line (trailing) or in the contiguous comment block
10
+ # ending on the line directly above it. Adjacency is the point — a
11
+ # marker elsewhere in the file justifies nothing. Host cops provide
12
+ # `justification_marker`, or pass an explicit `marker:` per call. A
13
+ # String marker matches by substring (suits multi-word phrases); a
14
+ # Regexp marker matches by `match?` against the downcased comment text
15
+ # (use `\b` anchors for single-word markers, where substring matching
16
+ # would let "enumeration" satisfy an `enum` marker).
12
17
  #
13
18
  # With `standalone_only: true` the upward walk only crosses comment-ONLY
14
19
  # lines. Use this when the checked node is a class/module declaration:
@@ -17,8 +22,8 @@ module RuboCop
17
22
  module AdjacentJustification
18
23
  private
19
24
 
20
- def adjacent_justification?(node, standalone_only: false)
21
- marker = justification_marker.downcase
25
+ def adjacent_justification?(node, standalone_only: false, marker: justification_marker)
26
+ marker = marker.downcase if marker.is_a?(String)
22
27
  comments_by_line = processed_source.comments.group_by { |comment| comment.location.line }
23
28
 
24
29
  return true if contains_marker?(comments_by_line[node.first_line], marker)
@@ -46,7 +51,10 @@ module RuboCop
46
51
  end
47
52
 
48
53
  def contains_marker?(comments, marker)
49
- Array(comments).any? { |comment| comment.text.downcase.include?(marker) }
54
+ Array(comments).any? do |comment|
55
+ text = comment.text.downcase
56
+ marker.is_a?(Regexp) ? marker.match?(text) : text.include?(marker)
57
+ end
50
58
  end
51
59
  end
52
60
  end
@@ -44,9 +44,7 @@ module RuboCop
44
44
  # add_column :checklists, :approval_required, :boolean
45
45
  #
46
46
  # ✔️ enum; "unset" is explicit, null: false is justified
47
- # # rubocop:disable DevDoc/Migration/AvoidNonNull -- enum
48
- # add_column :checklists, :approval_requirement, :integer, null: false
49
- # # rubocop:enable DevDoc/Migration/AvoidNonNull
47
+ # add_column :checklists, :approval_requirement, :integer, null: false # enum
50
48
  #
51
49
  # class Checklist < ApplicationRecord
52
50
  # enum :approval_requirement, { no_approval_needed: 0, approval_by_admins: 1 }
@@ -76,7 +74,7 @@ module RuboCop
76
74
  #
77
75
  # ✔️ true binary preference, justified
78
76
  # # rubocop:disable DevDoc/Migration/AvoidBooleanColumn -- true binary preference; user opt-in
79
- # add_column :service_subscriptions, :auto_renew, :boolean, null: false
77
+ # add_column :service_subscriptions, :auto_renew, :boolean, null: false # boolean
80
78
  # # rubocop:enable DevDoc/Migration/AvoidBooleanColumn
81
79
  #
82
80
  # NOTE: This cop catches `t.boolean`, `add_column ..., :boolean`,
@@ -104,7 +102,7 @@ module RuboCop
104
102
  #
105
103
  # # good (justified boolean)
106
104
  # # rubocop:disable DevDoc/Migration/AvoidBooleanColumn -- true binary preference
107
- # add_column :service_subscriptions, :auto_renew, :boolean, null: false
105
+ # add_column :service_subscriptions, :auto_renew, :boolean, null: false # boolean
108
106
  # # rubocop:enable DevDoc/Migration/AvoidBooleanColumn
109
107
  class AvoidBooleanColumn < Base
110
108
  MSG = 'Avoid `boolean` columns; consider a timestamp (approved_at), enum, or model method. ' \
@@ -1,3 +1,5 @@
1
+ require_relative '../auth/adjacent_justification'
2
+
1
3
  module RuboCop
2
4
  module Cop
3
5
  module DevDoc
@@ -50,34 +52,54 @@ module RuboCop
50
52
  # violation), so `null: false` is required, and enforced from the model
51
53
  # side by `DevDoc/Rails/EnumColumnNotNull`. But an enum is a plain
52
54
  # `integer` column, statically indistinguishable from any other
53
- # integer, so THIS cop cannot detect it and WILL flag it. Disable it on
54
- # the line with a brief reason `-- enum` so the migration is
55
- # self-documenting: a reader sees at a glance that the column is an enum.
55
+ # integer, so THIS cop cannot detect it and WILL flag it. Mark the line
56
+ # with an adjacent `# enum` comment (see Markers below) so the
57
+ # migration is self-documenting: a reader sees at a glance that the
58
+ # column is an enum.
56
59
  # - **Boolean columns justified via `DevDoc/Migration/AvoidBooleanColumn`**
57
60
  # — once the developer has justified a boolean through that cop's
58
61
  # escape hatch, NULL is outside {true, false} (just as it is outside an
59
62
  # enum's domain), so `null: false` is required and enforced by the
60
- # sibling cop `DevDoc/Migration/BooleanColumnNotNull`. Disable this cop
61
- # on the line with `-- boolean` so the migration is self-documenting.
63
+ # sibling cop `DevDoc/Migration/BooleanColumnNotNull`. Mark the line
64
+ # with an adjacent `# boolean` comment.
65
+ #
66
+ # ## Markers
67
+ # The marker is a comment containing the word `enum` or `boolean`, either
68
+ # trailing the flagged line itself or in the contiguous COMMENT-ONLY
69
+ # block ending on the line directly above it. A marker trailing a
70
+ # *previous code line* deliberately does not count — otherwise one
71
+ # marked column would silence the unmarked column defined on the next
72
+ # line. Matching is case-insensitive and word-bounded (exactly `enum` /
73
+ # `boolean`): a prose comment like `# enum — NULL is outside the
74
+ # enum's domain` satisfies the marker, while `enumeration`, `enums`,
75
+ # or `enum_type` do not. Adjacency is the point — a marker elsewhere
76
+ # in the file justifies nothing.
62
77
  #
63
78
  # ✔️ Required foreign key (never flagged)
64
79
  # t.belongs_to :user, null: false, foreign_key: true
65
80
  #
66
- # ✔️ Enum (flagged here disable with a brief `-- enum` reason)
67
- # # rubocop:disable DevDoc/Migration/AvoidNonNull -- enum
81
+ # ✔️ Enum, marker trailing the line
82
+ # add_column :orders, :status, :integer, null: false # enum
83
+ #
84
+ # ✔️ Enum, marker in the comment above
85
+ # # enum — NULL is outside the enum's domain
68
86
  # add_column :orders, :status, :integer, null: false
69
- # # rubocop:enable DevDoc/Migration/AvoidNonNull
70
87
  #
71
- # ✔️ Boolean (flagged here disable with a brief `-- boolean` reason)
72
- # # rubocop:disable DevDoc/Migration/AvoidNonNull -- boolean
88
+ # ✔️ Boolean (justified through AvoidBooleanColumn's escape hatch)
73
89
  # # rubocop:disable DevDoc/Migration/AvoidBooleanColumn -- true binary preference
74
- # add_column :things, :flag, :boolean, null: false
90
+ # add_column :things, :flag, :boolean, null: false # boolean
75
91
  # # rubocop:enable DevDoc/Migration/AvoidBooleanColumn
76
- # # rubocop:enable DevDoc/Migration/AvoidNonNull
92
+ #
93
+ # A `# rubocop:disable` directive still silences the cop like any other
94
+ # (RuboCop-level behavior), but the marker is the sanctioned form —
95
+ # consumer projects that police inline disables (e.g. via
96
+ # `Style/DisableCopsWithinSourceCodeDirective`'s `AllowedCops`) can drop
97
+ # this cop from their allowed-disables list once existing sites carry
98
+ # markers.
77
99
  #
78
100
  # NOTE: This cop is deliberately NOT enum-aware. It could read the
79
101
  # model's `enum` declarations and skip those columns, but requiring an
80
- # explicit per-line disable is intentional: it forces the developer to
102
+ # explicit per-line marker is intentional: it forces the developer to
81
103
  # signal that the column is an enum, which documents the migration. A
82
104
  # silent skip would hide that intent.
83
105
  #
@@ -85,8 +107,10 @@ module RuboCop
85
107
  # API: `change_column_null(table, column, false)` and
86
108
  # `change_column(table, column, type, null: false)`. Both express the same
87
109
  # constraint as `null: false` on a definition (the add-nullable -> backfill
88
- # -> tighten step), so a legit enum/boolean tightening disables this cop
89
- # inline with `-- enum`/`-- boolean`, exactly as for a new column.
110
+ # -> tighten step), so a legit enum/boolean tightening carries the same
111
+ # `# enum`/`# boolean` marker, exactly as for a new column. When the
112
+ # tightening runs inside a loop, put the marker on the line of the
113
+ # `change_column_null` call itself.
90
114
  #
91
115
  # NOTE: This cop only flags `null: false` (and the equivalent `false` arg
92
116
  # of `change_column_null`). It does not flag `null: true` (redundant but
@@ -105,17 +129,27 @@ module RuboCop
105
129
  # # bad (same tightening, via change_column)
106
130
  # change_column :users, :name, :string, null: false
107
131
  #
108
- # # bad (enum without a disable — the cop flags it; disable with `-- enum`)
132
+ # # bad (enum without a marker — the cop flags it)
109
133
  # t.integer :processing_status, null: false
110
134
  #
111
135
  # # good
112
136
  # add_column :users, :name, :string
113
137
  #
138
+ # # good (enum, marked)
139
+ # t.integer :processing_status, null: false # enum
140
+ #
114
141
  # # good (required foreign key — never flagged)
115
142
  # t.belongs_to :user, null: false, foreign_key: true
116
143
  class AvoidNonNull < Base
144
+ include Auth::AdjacentJustification
145
+
117
146
  MSG = 'Avoid `null: false` on regular columns; enforce presence in the model layer. ' \
118
- 'If this is an enum column, disable this cop on the line with a brief reason, e.g. `-- enum`.'.freeze
147
+ 'If this is an enum or justified boolean column, mark the line with an adjacent ' \
148
+ '`# enum` / `# boolean` comment.'.freeze
149
+
150
+ # Word-bounded so an incidental "enumeration" in a comment cannot
151
+ # satisfy the marker. Comment text is downcased before matching.
152
+ KIND_MARKER = /\b(?:enum|boolean)\b/
119
153
 
120
154
  # Column-definition helpers that take a `null:` option. Deliberately
121
155
  # EXCLUDES `references` / `belongs_to` (and the separate `add_reference`
@@ -139,14 +173,17 @@ module RuboCop
139
173
  # step. Flagged so the cop cannot be sidestepped by choice of API: a
140
174
  # regular column tightened to NOT NULL is held to the same standard as one
141
175
  # declared NOT NULL up front. A legit enum/boolean tightening resolves at
142
- # the disable site, exactly as for a new column.
176
+ # the marker site, exactly as for a new column.
143
177
  def_node_matcher :change_column_null_false, <<~PATTERN
144
178
  (send _ :change_column_null _ _ $false ...)
145
179
  PATTERN
146
180
 
147
181
  def on_send(node)
148
182
  flag = offense_node(node)
149
- add_offense(flag) if flag
183
+ return unless flag
184
+ return if kind_marker?(node, flag)
185
+
186
+ add_offense(flag)
150
187
  end
151
188
 
152
189
  private
@@ -158,6 +195,17 @@ module RuboCop
158
195
  change_column_null_false(node) || column_null_false_pair(node)
159
196
  end
160
197
 
198
+ # Checked from both the call's first line and the offending
199
+ # `null: false` pair's own line, so a multi-line call accepts the
200
+ # marker trailing either. standalone_only: the upward walk crosses
201
+ # comment-only lines exclusively — a marker trailing a PREVIOUS code
202
+ # line (the column defined one line up, the enclosing create_table,
203
+ # an earlier argument of this very call) must not silence this one.
204
+ def kind_marker?(node, flag)
205
+ adjacent_justification?(node, marker: KIND_MARKER, standalone_only: true) ||
206
+ adjacent_justification?(flag, marker: KIND_MARKER, standalone_only: true)
207
+ end
208
+
161
209
  def column_null_false_pair(node)
162
210
  return unless column_method?(node)
163
211
 
@@ -24,8 +24,8 @@ module RuboCop
24
24
  # the boolean case: that cop flags `null: false` on regular
25
25
  # columns (including booleans, which it cannot distinguish from
26
26
  # other types); this cop REQUIRES `null: false` on booleans. The
27
- # contradiction is resolved at the disable site: when the
28
- # developer disables `AvoidNonNull` on a boolean with `-- boolean`
27
+ # contradiction is resolved at the marker site: when the
28
+ # developer marks the `AvoidNonNull` line with `# boolean`
29
29
  # (alongside the `AvoidBooleanColumn` disable), this cop fires if
30
30
  # `null: false` is missing.
31
31
  #
@@ -47,9 +47,7 @@ module RuboCop
47
47
  # end
48
48
  # end
49
49
  #
50
- # # rubocop:disable DevDoc/Migration/AvoidNonNull -- boolean
51
- # change_column_null :table, :flag, false
52
- # # rubocop:enable DevDoc/Migration/AvoidNonNull
50
+ # change_column_null :table, :flag, false # boolean
53
51
  # end
54
52
  #
55
53
  # The application layer is the source of truth for the default
@@ -0,0 +1,56 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Rails
5
+ # Inherit the app's `ApplicationModel` root instead of including
6
+ # `ActiveModel::Model` directly in a class under `app/models`.
7
+ #
8
+ # ## Rationale
9
+ # Table-less form-backed domain objects follow the three-way rule
10
+ # (backend/03_model.md item 9): persisted classes inherit
11
+ # `ApplicationRecord`, form-backed POROs inherit `ApplicationModel`
12
+ # (a thin app root over `Glib::Model`, which carries the shared
13
+ # mechanics such as `attr_id_list`), and plain domain logic inherits
14
+ # `PlainModel`. A direct `include ActiveModel::Model` bypasses the
15
+ # shared root: the class silently misses the shared mechanics, and the
16
+ # author never makes the which-kind-is-this decision the rule exists
17
+ # to force. This is the ActiveModel analog of `Rails/ApplicationRecord`.
18
+ #
19
+ # This cop gives editor-time feedback on the single most common direct
20
+ # mistake; totality (every model class descends from one of the three
21
+ # bases, through any intermediate family base) is enforced at test time
22
+ # by `DevDoc::Test::Lints::DomainClassBase`, since resolving indirect
23
+ # ancestry is beyond per-file static analysis.
24
+ #
25
+ # Disabled by default: enable it in projects whose `ApplicationModel`
26
+ # root exists (it requires glib-web's `Glib::Model`).
27
+ #
28
+ # @example
29
+ # # bad
30
+ # class BulkOperation
31
+ # include ActiveModel::Model
32
+ # end
33
+ #
34
+ # # good
35
+ # class BulkOperation < ApplicationModel
36
+ # end
37
+ class ApplicationModelBase < Base
38
+ MSG = 'Inherit `ApplicationModel` instead of including `ActiveModel::Model` directly — ' \
39
+ 'the shared root carries the form-object mechanics (backend/03_model.md item 9).'.freeze
40
+
41
+ RESTRICT_ON_SEND = %i[include].freeze
42
+
43
+ def_node_matcher :active_model_include?, <<~PATTERN
44
+ (send nil? :include (const (const {nil? cbase} :ActiveModel) :Model))
45
+ PATTERN
46
+
47
+ def on_send(node)
48
+ return unless active_model_include?(node)
49
+
50
+ add_offense(node)
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -27,12 +27,11 @@ module RuboCop
27
27
  # ## Interaction with AvoidNonNull
28
28
  # An enum is a plain `integer` column, so `AvoidNonNull` cannot tell it
29
29
  # apart from a regular integer and WILL flag the `null: false` you add
30
- # to satisfy this cop. Disable it on that migration with a brief `-- enum`
31
- # reason, so the migration is self-documenting:
30
+ # to satisfy this cop. Mark the migration line with an adjacent `# enum`
31
+ # comment (that cop's sanctioned marker), so the migration is
32
+ # self-documenting:
32
33
  #
33
- # # rubocop:disable DevDoc/Migration/AvoidNonNull -- enum
34
- # add_column :orders, :status, :integer, null: false
35
- # # rubocop:enable DevDoc/Migration/AvoidNonNull
34
+ # add_column :orders, :status, :integer, null: false # enum
36
35
  #
37
36
  # NOTE: This cop reads `db/schema.rb` and does nothing if it is absent
38
37
  # (e.g. projects using `structure.sql`). It also relies on the schema
@@ -0,0 +1,129 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Rails
5
+ # Controllers must not call association `*_ids=` writers; the write
6
+ # belongs behind the model method or form-object PORO that owns the
7
+ # operation's validations.
8
+ #
9
+ # ## Rationale
10
+ # `collection_ids=` looks like plain attribute assignment but is not:
11
+ # on a persisted record it writes the join table IMMEDIATELY — no save
12
+ # call, no validations, no surrounding transaction. In a controller
13
+ # that produces two failure modes:
14
+ #
15
+ # - **Validation asymmetry.** The create path routes through a form
16
+ # object whose validations guard the association (say, "at least one
17
+ # tag"); a later-added update action assigns `record.tag_ids = ...`
18
+ # directly, and every one of those guards silently stops existing on
19
+ # the second write path. Nothing fails loudly — the update simply
20
+ # never consults the rules that create enforces.
21
+ # - **Partial writes.** The association mutates even when the
22
+ # surrounding operation fails afterwards: clear `record.tag_ids = []`
23
+ # and then fail to save a status flag, and the two halves are left
24
+ # inconsistent with no transaction to roll the join rows back.
25
+ #
26
+ # Both are the data-saving-orchestration placement rule (see the
27
+ # orchestration best-practice doc, category 1) wearing an assignment
28
+ # costume: which rows must land together, and under which guards, is
29
+ # domain knowledge. Move the write into a model method or the
30
+ # form-object PORO that owns the operation's validations, so updates
31
+ # travel the same validation path as creates.
32
+ #
33
+ # ❌ Hand-rolled update path — join rows written before save!, guards skipped
34
+ # def update
35
+ # @article.category = update_params[:category]
36
+ # @article.tag_ids = checked_tag_ids
37
+ # @article.save!
38
+ # end
39
+ #
40
+ # ✔️ The model method owns the write and its guards
41
+ # def update
42
+ # @article.update_with_tags!(update_params, tag_ids: checked_tag_ids)
43
+ # end
44
+ #
45
+ # ## Relationship with DevDoc/Rails/AvoidBypassingValidation
46
+ # Same bypass family, different signal: that cop matches a fixed list
47
+ # of ActiveRecord method names repo-wide, while `*_ids=` is a NAME
48
+ # PATTERN that is perfectly legitimate on form objects (common under
49
+ # `app/models/`). The pattern is only dependable where a direct ids
50
+ # write is either a validation bypass or misplaced orchestration —
51
+ # controllers — so it lives in this scoped cop instead.
52
+ #
53
+ # ## Exception
54
+ # The receiver's type is statically invisible, so this cop flags every
55
+ # `*_ids=` spelling, including ones that persist nothing: an `ActiveModel`
56
+ # form object, a not-yet-saved record (its ids apply at save time, under
57
+ # validations), or a non-AR object such as a presenter or OpenStruct.
58
+ # Those are ordinary params→object binding (orchestration category 2) —
59
+ # disable inline, naming why nothing persists:
60
+ #
61
+ # # rubocop:disable DevDoc/Rails/NoCollectionIdsWriterInController
62
+ # # -- ArticleImport is an ActiveModel PORO; nothing persists
63
+ #
64
+ # # rubocop:disable DevDoc/Rails/NoCollectionIdsWriterInController
65
+ # # -- @article is built in this action and unsaved; ids apply at save,
66
+ # # under validations
67
+ #
68
+ # NOTE: Spellings with the same immediate-write behavior that this cop
69
+ # cannot see, for reviewers: the plain collection writer
70
+ # (`record.tags = [...]`) — indistinguishable from an attribute write —
71
+ # a STANDALONE `assign_attributes(tag_ids: [...])` on a persisted record
72
+ # (mass assignment invokes the same writer, with no transaction around
73
+ # it), and dynamic dispatch (`record.send(:tag_ids=, x)`). By contrast,
74
+ # `update`/`update!` with an ids key is NOT in this class: Rails wraps
75
+ # assign_attributes + save in a transaction precisely so those join-row
76
+ # writes roll back when validations fail (see the comment inside
77
+ # `ActiveRecord::Persistence#update!`).
78
+ #
79
+ # @example
80
+ # # bad
81
+ # @article.tag_ids = checked_tag_ids
82
+ #
83
+ # # bad
84
+ # article&.tag_ids = []
85
+ #
86
+ # # bad — op-assign calls the same writer
87
+ # @article.tag_ids += [tag.id]
88
+ #
89
+ # # good — the model method owns the write and its validations
90
+ # @article.update_with_tags!(update_params, tag_ids: checked_tag_ids)
91
+ class NoCollectionIdsWriterInController < Base
92
+ MSG = '`%<method>s` in a controller — on a persisted record a collection `_ids=` writer ' \
93
+ 'updates the join table immediately, skipping the owner\'s save and validations. Move the ' \
94
+ 'write into the model method or form-object PORO that owns the operation\'s validations.'.freeze
95
+
96
+ # Dynamic name pattern, so RESTRICT_ON_SEND cannot apply (it is
97
+ # static); the filter runs inside on_send instead.
98
+ IDS_WRITER = /\A\w+_ids=\z/
99
+
100
+ def on_send(node)
101
+ return unless node.assignment_method?
102
+ return unless IDS_WRITER.match?(node.method_name.to_s)
103
+
104
+ add_offense(node.loc.selector, message: format(MSG, method: node.method_name))
105
+ end
106
+
107
+ # Safe navigation (`record&.tag_ids = x`) parses as a csend node that
108
+ # on_send does not receive — alias it so `&.` is caught too.
109
+ alias on_csend on_send
110
+
111
+ # Op-assigns (`record.tag_ids += [x]`, `||=`, `&&=`) call the same
112
+ # writer but parse as op_asgn/or_asgn/and_asgn nodes whose inner send
113
+ # is the READER (`tag_ids`, no `=`), so on_send never sees a match.
114
+ def on_op_asgn(node)
115
+ lhs = node.children.first
116
+ return unless lhs.type?(:send, :csend)
117
+
118
+ writer = "#{lhs.method_name}="
119
+ return unless IDS_WRITER.match?(writer)
120
+
121
+ add_offense(lhs.loc.selector, message: format(MSG, method: writer))
122
+ end
123
+ alias on_or_asgn on_op_asgn
124
+ alias on_and_asgn on_op_asgn
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
@@ -1,5 +1,5 @@
1
1
  module RuboCop
2
2
  module DevDoc
3
- VERSION = "0.15.0".freeze
3
+ VERSION = "0.17.0".freeze
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rubocop-dev_doc
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.15.0
4
+ version: 0.17.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - dev-doc contributors
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-08-24 00:00:00.000000000 Z
11
+ date: 2026-08-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -95,6 +95,7 @@ files:
95
95
  - lib/dev_doc/test/lints/cron_schedule.rb
96
96
  - lib/dev_doc/test/lints/cross_tenant_canary_check.rb
97
97
  - lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb
98
+ - lib/dev_doc/test/lints/domain_class_base.rb
98
99
  - lib/dev_doc/test/lints/duplicate_snapshot.rb
99
100
  - lib/dev_doc/test/lints/enqueue_disable_naming.rb
100
101
  - lib/dev_doc/test/lints/external_io_boundary.rb
@@ -133,6 +134,7 @@ files:
133
134
  - lib/rubocop/cop/dev_doc/migration/require_primary_key.rb
134
135
  - lib/rubocop/cop/dev_doc/migration/require_reference_foreign_key.rb
135
136
  - lib/rubocop/cop/dev_doc/migration/require_timestamps.rb
137
+ - lib/rubocop/cop/dev_doc/rails/application_model_base.rb
136
138
  - lib/rubocop/cop/dev_doc/rails/application_record_transaction.rb
137
139
  - lib/rubocop/cop/dev_doc/rails/avoid_bypassing_validation.rb
138
140
  - lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb
@@ -143,6 +145,7 @@ files:
143
145
  - lib/rubocop/cop/dev_doc/rails/enum_column_not_null.rb
144
146
  - lib/rubocop/cop/dev_doc/rails/enum_must_be_symbolized.rb
145
147
  - lib/rubocop/cop/dev_doc/rails/no_block_predicate_on_relation.rb
148
+ - lib/rubocop/cop/dev_doc/rails/no_collection_ids_writer_in_controller.rb
146
149
  - lib/rubocop/cop/dev_doc/rails/no_deliver_later_in_transaction.rb
147
150
  - lib/rubocop/cop/dev_doc/rails/no_manual_record_invalid.rb
148
151
  - lib/rubocop/cop/dev_doc/rails/no_perform_later_in_model.rb