rubocop-dev_doc 0.17.0 → 0.19.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.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/config/default.yml +461 -62
  3. data/config/obsoletion.yml +7 -3
  4. data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
  5. data/lib/dev_doc/i18n/tasks.rb +68 -0
  6. data/lib/dev_doc/railtie.rb +19 -0
  7. data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
  8. data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +8 -3
  9. data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +4 -0
  10. data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
  11. data/lib/dev_doc/test/pseudo_i18n_crawler.rb +9 -0
  12. data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
  13. data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
  14. data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
  15. data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
  16. data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
  17. data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
  18. data/lib/rubocop/cop/dev_doc/i18n/hardcoded_text.rb +243 -0
  19. data/lib/rubocop/cop/dev_doc/i18n/localizable_props.rb +69 -19
  20. data/lib/rubocop/cop/dev_doc/i18n/require_translation.rb +13 -17
  21. data/lib/rubocop/cop/dev_doc/i18n/text_shape.rb +94 -0
  22. data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
  23. data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
  24. data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
  25. data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
  26. data/lib/rubocop/cop/dev_doc/rails/avoid_bypassing_validation.rb +81 -26
  27. data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
  28. data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
  29. data/lib/rubocop/cop/dev_doc/rails/no_errors_add_in_controller.rb +177 -0
  30. data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +236 -0
  31. data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
  32. data/lib/rubocop/cop/dev_doc/style/in_memory_association_find.rb +162 -0
  33. data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +279 -0
  34. data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
  35. data/lib/rubocop/cop/dev_doc/style/prefer_allowlist_symbol_param.rb +193 -0
  36. data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
  37. data/lib/rubocop/cop/dev_doc/style/use_g_log.rb +133 -0
  38. data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
  39. data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
  40. data/lib/rubocop/cop/dev_doc/test/prefer_find_sole_by.rb +146 -0
  41. data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
  42. data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
  43. data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
  44. data/lib/rubocop/cop/dev_doc/test/test_name_special_characters.rb +108 -0
  45. data/lib/rubocop/cop/dev_doc/view/prefer_prop_over_name.rb +11 -1
  46. data/lib/rubocop/dev_doc/version.rb +1 -1
  47. metadata +24 -4
  48. data/lib/rubocop/cop/dev_doc/i18n/report_text.rb +0 -76
@@ -3,7 +3,7 @@ module RuboCop
3
3
  module DevDoc
4
4
  module I18n
5
5
  # Shared traversal for the glib JSON-UI localization cops
6
- # (`RequireTranslation`, `ReportText`).
6
+ # (`RequireTranslation`).
7
7
  #
8
8
  # It locates user-facing text values on watched glib component calls and
9
9
  # hands each `(key, value_node)` to the including cop's
@@ -23,22 +23,84 @@ module RuboCop
23
23
  DEFAULT_WATCHED_METHODS = %w[
24
24
  h1 h2 h3 h4 h5 h6 p label markdown html
25
25
  button switch chip progressCircle shareButton
26
- fields_text fields_number fields_select fields_password
27
- fields_textarea fields_check fields_checkGroup fields_chipGroup
28
- fields_timeZone fields_radioGroup fields_date fields_datetime
29
- fields_upload
26
+ fields_text fields_number fields_email fields_url fields_password
27
+ fields_timer fields_submit fields_textarea fields_richText
28
+ fields_select fields_dynamicSelect fields_dynamicGroup
29
+ fields_check fields_checkGroup fields_chipGroup fields_radio
30
+ fields_radioGroup fields_timeZone fields_date fields_datetime
31
+ fields_file fields_upload fields_sign fields_location fields_phone
32
+ fields_otp fields_captcha fields_rating fields_creditCard
33
+ fields_stripeToken fields_stripeExternalAccount
30
34
  dialogs_alert dialogs_notification
31
35
  snackbars_alert snackbars_select
32
36
  banners_alert banners_select
33
37
  ].freeze
34
38
 
35
39
  DEFAULT_LOCALIZABLE_KEYS = %w[
36
- title subtitle subsubtitle label placeholder text
40
+ title subtitle subsubtitle label placeholder hint text
37
41
  message description uploadText leftText rightText onLabel
38
42
  ].freeze
39
43
 
40
44
  TRANSLATION_METHODS = %i[t translate].freeze
41
45
 
46
+ # Whether `node` is a value this traversal hands to the cop: a
47
+ # localizable key's value on a watched call, at any hash/array depth,
48
+ # or a jbuilder positional argument. HardcodedText skips these so one
49
+ # literal isn't reported by both cops.
50
+ def self.inspected_value?(node, watched_methods, localizable_keys)
51
+ parent = node.parent
52
+ return false unless parent
53
+
54
+ if parent.pair_type?
55
+ localizable_pair_value?(parent, node, localizable_keys) &&
56
+ watched_call_argument?(parent.parent, watched_methods)
57
+ elsif parent.call_type?
58
+ jbuilder_positional_value?(parent, node, localizable_keys)
59
+ else
60
+ false
61
+ end
62
+ end
63
+
64
+ def self.localizable_pair_value?(pair, node, localizable_keys)
65
+ pair.value.equal?(node) && pair.key.sym_type? && localizable_keys.include?(pair.key.value.to_s)
66
+ end
67
+
68
+ def self.jbuilder_positional_value?(call, node, localizable_keys)
69
+ call.first_argument.equal?(node) && localizable_keys.include?(call.method_name.to_s) &&
70
+ json_receiver?(call.receiver)
71
+ end
72
+
73
+ # Climbs out of the nested hashes and arrays `each_localizable` walks
74
+ # into, then checks the call they are an argument of.
75
+ def self.watched_call_argument?(container, watched_methods)
76
+ current = container
77
+ current = current.parent.pair_type? ? current.parent.parent : current.parent while nested_value?(current)
78
+ call = current.parent
79
+ return false unless call&.call_type? && watched_methods.include?(call.method_name.to_s)
80
+
81
+ call.arguments.any? { |arg| arg.equal?(current) }
82
+ end
83
+
84
+ def self.nested_value?(node)
85
+ parent = node.parent
86
+ return false unless parent
87
+
88
+ parent.array_type? || (parent.pair_type? && parent.value.equal?(node))
89
+ end
90
+
91
+ def self.translated_interpolation?(node)
92
+ node.each_descendant(:send, :csend).any? do |call|
93
+ TRANSLATION_METHODS.include?(call.method_name)
94
+ end
95
+ end
96
+
97
+ def self.json_receiver?(node)
98
+ return false unless node
99
+
100
+ (node.send_type? && node.method_name == :json && node.receiver.nil?) ||
101
+ (node.lvar_type? && node.children.first == :json)
102
+ end
103
+
42
104
  def on_send(node)
43
105
  node.arguments.each { |arg| each_localizable(arg) } if watched_methods.include?(node.method_name.to_s)
44
106
 
@@ -76,7 +138,7 @@ module RuboCop
76
138
  # mistaken for localizable props.
77
139
  def check_jbuilder_positional(node)
78
140
  return unless localizable_keys.include?(node.method_name.to_s)
79
- return unless json_receiver?(node.receiver)
141
+ return unless LocalizableProps.json_receiver?(node.receiver)
80
142
 
81
143
  value = node.first_argument
82
144
  return unless value
@@ -84,18 +146,6 @@ module RuboCop
84
146
  inspect_localizable(node.method_name, value)
85
147
  end
86
148
 
87
- def json_receiver?(node)
88
- return false unless node
89
-
90
- (node.send_type? && node.method_name == :json && node.receiver.nil?) ||
91
- (node.lvar_type? && node.children.first == :json)
92
- end
93
-
94
- def translation_call?(node)
95
- (node.send_type? || node.csend_type?) &&
96
- TRANSLATION_METHODS.include?(node.method_name)
97
- end
98
-
99
149
  def watched_methods
100
150
  cop_config.fetch('WatchedMethods', DEFAULT_WATCHED_METHODS)
101
151
  end
@@ -14,12 +14,13 @@ module RuboCop
14
14
  #
15
15
  # Hash props (`view.p text: '...'`), nested hash props
16
16
  # (`view.icon tooltip: { text: '...' }`) and the jbuilder positional
17
- # form (`json.title '...'`) are all checked. Empty/whitespace strings
18
- # are ignored — they carry no user-facing text. An interpolated string
19
- # (`"Hi #{name}"`) is flagged because its literal portions are still
20
- # hardcoded copy — unless it interpolates a `t(...)` (or
21
- # `translate`/`I18n.t`) call, which is treated as positive localization
22
- # and left alone.
17
+ # form (`json.title '...'`) are all checked. Plain strings with no
18
+ # letters (blank, `'0'`, `'2025'`, `'%'`, `'-'`) are ignored — there is
19
+ # nothing in them to translate. An interpolated string is flagged even
20
+ # then: its literal portions are hardcoded copy (`"Hi #{name}"`) or a
21
+ # format that can differ by locale (`"#{n}%"`, `"#{a}, #{b}"`) —
22
+ # unless it interpolates a `t(...)` (or `translate`/`I18n.t`) call,
23
+ # which is treated as positive localization and left alone.
23
24
  #
24
25
  # The watched method names and localizable keys are configurable via
25
26
  # `WatchedMethods:` and `LocalizableKeys:`.
@@ -73,20 +74,15 @@ module RuboCop
73
74
  add_offense(value, message: format(MSG, key: key))
74
75
  end
75
76
 
76
- # A plain string literal is hardcoded copy unless it's blank. A `dstr`
77
- # (interpolated string) is hardcoded copy too — unless it interpolates
78
- # a translation call, which counts as positive localization.
77
+ # A plain string literal is hardcoded copy when it has a letter. A
78
+ # `dstr` (interpolated string) is hardcoded copy too — unless it
79
+ # interpolates a translation call, which counts as positive
80
+ # localization.
79
81
  def hardcoded_string?(node)
80
- return !localized_interpolation?(node) if node.dstr_type?
82
+ return !LocalizableProps.translated_interpolation?(node) if node.dstr_type?
81
83
  return false unless node.str_type?
82
84
 
83
- !node.value.strip.empty?
84
- end
85
-
86
- def localized_interpolation?(node)
87
- node.each_descendant(:send, :csend).any? do |call|
88
- TRANSLATION_METHODS.include?(call.method_name)
89
- end
85
+ node.value.match?(/\p{L}/)
90
86
  end
91
87
  end
92
88
  end
@@ -0,0 +1,94 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module I18n
5
+ # Decides whether a string literal's text reads like prose (copy a user
6
+ # could see) or like an identifier (a key, CSS class list, path, URL,
7
+ # constant, inline CSS, SQL or format string). Used by
8
+ # `DevDoc/I18n/HardcodedText`.
9
+ #
10
+ # Interpolations (`#{...}`) and format directives (`%<x>s`, `%{x}`,
11
+ # `%Y`) are replaced by PLACEHOLDER before judging: each counts as one
12
+ # word toward "two or more words" but contributes no letters, so
13
+ # `"#{n} items"` is prose while `"#{a}. #{b}"` and `"badge--#{x}"` are
14
+ # not.
15
+ module TextShape
16
+ PLACEHOLDER = "␀".freeze
17
+
18
+ FORMAT_DIRECTIVE = /%(?:<\w+>[a-z]|\{\w+\}|[-_0^#]?[a-zA-Z])/
19
+ HTML_TAG = %r{</?[a-zA-Z][^<>]*>}
20
+ HTML_ENTITY = /&#?\w+;/
21
+
22
+ LITERAL_WORD = /\p{L}{2,}/
23
+ NON_ASCII_LETTER = /(?=\p{L})[^\p{ASCII}]/
24
+ WORDISH = /\p{L}|␀/
25
+ CAPITALISED_WORD = /\A\p{Lu}\p{Ll}[\p{Ll}'’]*[.!?:…]?\z/
26
+
27
+ URL = %r{\A(?:[a-z][a-z0-9+.-]*://|mailto:|tel:|www\.)\S*\z}i
28
+ PATH = %r{\A[^\s/]*/\S*\z}
29
+ EMAIL = /\A[^\s@]+@[^\s@]+\z/
30
+ # Tailwind arbitrary values (`bg-[#0A2A9E]`) may hold uppercase hex,
31
+ # and `!` marks an important modifier at either end (`!px-4`, `px-4!`).
32
+ IDENTIFIER_TOKEN = %r{\A!?(?:[a-z0-9_.:\-\[\]#/?=&*␀]|-\[[^\]\s]*\])+!?\z}
33
+ IDENTIFIER_SEPARATOR = %r{[-_./:#]}
34
+ CONSTANT_PATH = /\A[A-Z]\w*(?:::[A-Z]\w*)+\z/
35
+ SCREAMING_TOKEN = /\A[A-Z0-9_\-␀]+\z/
36
+ CAMEL_CASE_TOKEN = /\A(?:[a-z]+|[A-Z][a-z0-9]+)(?:[A-Z][a-z0-9]*)+\z/
37
+ SINGLE_TOKEN_NON_TEXT = [
38
+ URL, PATH, EMAIL, IDENTIFIER_TOKEN, CONSTANT_PATH, SCREAMING_TOKEN, CAMEL_CASE_TOKEN
39
+ ].freeze
40
+
41
+ CSS_DECLARATIONS = /\A(?:\s*[a-z-]+\s*:\s*[^;:]+;)+\s*(?:[a-z-]+\s*:\s*[^;:]+)?\s*\z/
42
+ SQL = /
43
+ \b(?:SELECT|INSERT\s+INTO|DELETE\s+FROM|WHERE|JOIN|COALESCE|ILIKE|ORDER\s+BY|GROUP\s+BY|
44
+ IS\s+(?:NOT\s+)?NULL|CASE\s+WHEN|ASC|DESC)\b
45
+ | (?:=|<>|!=|>=|<=|\bLIKE|\bIN)\s*\(?\s*(?:\?|:\w)
46
+ | ->>?
47
+ | \b(?:COUNT|SUM|AVG|MIN|MAX|CAST|DATE|DATE_DIFF|DATE_TRUNC|FORMAT_DATE|EXTRACT|NULLIF)\(
48
+ | (?:\)|\b[a-z0-9_]\w*)\s+AS\s+(?:[a-z_]\w*|␀)
49
+ | \b(?:AND|OR)\s+\(?\s*[a-z_][\w.]*\s*(?:[=<>!]|\b(?:IS|IN|LIKE|ILIKE|BETWEEN)\b)
50
+ /x
51
+
52
+ module_function
53
+
54
+ def prose?(raw)
55
+ text = normalize(raw)
56
+ return false unless text.match?(LITERAL_WORD) || text.match?(NON_ASCII_LETTER)
57
+ return false if non_text?(text)
58
+
59
+ tokens = text.split
60
+ return tokens.count { |token| token.match?(WORDISH) } >= 2 if tokens.size >= 2
61
+
62
+ text.match?(CAPITALISED_WORD) || text.match?(NON_ASCII_LETTER)
63
+ end
64
+
65
+ def normalize(raw)
66
+ raw.gsub(FORMAT_DIRECTIVE, PLACEHOLDER)
67
+ .gsub(HTML_TAG, ' ')
68
+ .gsub(HTML_ENTITY, ' ')
69
+ .strip
70
+ end
71
+
72
+ def non_text?(text)
73
+ return true if text.match?(SQL)
74
+ return true if text.match?(CSS_DECLARATIONS) && (text.include?(';') || text.match?(/\A[a-z]+-[a-z]/))
75
+
76
+ tokens = text.split
77
+ return SINGLE_TOKEN_NON_TEXT.any? { |pattern| text.match?(pattern) } if tokens.size == 1
78
+
79
+ identifier_list?(tokens)
80
+ end
81
+
82
+ # A CSS class list or similar: every token lowercase and
83
+ # identifier-shaped, at least one with a separator (`card card--active`).
84
+ # A plain lowercase phrase (`not yet submitted`) has no separator and
85
+ # stays prose.
86
+ def identifier_list?(tokens)
87
+ tokens.all? { |token| token.match?(IDENTIFIER_TOKEN) } &&
88
+ tokens.any? { |token| token.match?(IDENTIFIER_SEPARATOR) }
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -81,7 +81,7 @@ module RuboCop
81
81
  end
82
82
 
83
83
  def allowed_prefixes
84
- Array(cop_config['AllowedPrefixes'])
84
+ Array(cop_config['AllowedPrefixes']) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one prefix or a list
85
85
  end
86
86
 
87
87
  def prefixes_display(prefixes)
@@ -0,0 +1,26 @@
1
+ module RuboCop
2
+ module Cop
3
+ module DevDoc
4
+ module Migration
5
+ # Shared by the reference-option cops: the `ActiveRecord::Migration
6
+ # [4.2]` compatibility layer flips the reference default to
7
+ # `index: false` (see compatibility.rb's V4_2), so inside such a
8
+ # class `index: true` is load-bearing and `index: false` restates
9
+ # the default. Those migrations are skipped entirely.
10
+ module LegacyMigration
11
+ private
12
+
13
+ def legacy_migration?(node)
14
+ node.each_ancestor(:class).any? do |klass|
15
+ superclass = klass.children[1]
16
+ next false unless superclass&.send_type? && superclass.method?(:[])
17
+
18
+ version = superclass.first_argument
19
+ version&.numeric_type? && version.value < 5.0
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -1,4 +1,5 @@
1
1
  require_relative '../hash_pair_removal'
2
+ require_relative 'legacy_migration'
2
3
 
3
4
  module RuboCop
4
5
  module Cop
@@ -14,8 +15,9 @@ module RuboCop
14
15
  # (and imply, wrongly, that references without it are unindexed).
15
16
  #
16
17
  # The option is only meaningful when it *overrides* the default:
17
- # `index: false` to opt out, or a hash to customize
18
- # (`index: { unique: true }`). Those forms pass untouched.
18
+ # a hash to customize (`index: { unique: true }`) passes untouched;
19
+ # a literal `index: false` removes the index and is banned by the
20
+ # sibling cop `DevDoc/Migration/RequireReferenceIndex`.
19
21
  #
20
22
  # ❌ Redundant — this index exists anyway
21
23
  # t.belongs_to :user, foreign_key: true, null: false, index: true
@@ -55,6 +57,7 @@ module RuboCop
55
57
  class RedundantReferenceIndex < Base
56
58
  extend AutoCorrector
57
59
  include HashPairRemoval
60
+ include LegacyMigration
58
61
 
59
62
  MSG = '`index: true` is redundant — references are indexed by default since Rails 5.'.freeze
60
63
 
@@ -70,19 +73,6 @@ module RuboCop
70
73
 
71
74
  private
72
75
 
73
- # `ActiveRecord::Migration[4.2]` compatibility flips the reference
74
- # default to `index: false` (see compatibility.rb's V4_2), so inside
75
- # such a class `index: true` is load-bearing, not redundant.
76
- def legacy_migration?(node)
77
- node.each_ancestor(:class).any? do |klass|
78
- superclass = klass.children[1]
79
- next false unless superclass&.send_type? && superclass.method?(:[])
80
-
81
- version = superclass.first_argument
82
- version&.numeric_type? && version.value < 5.0
83
- end
84
- end
85
-
86
76
  def check_pair(node, options, pair)
87
77
  return unless index_key?(pair.key) && pair.value.true_type?
88
78
 
@@ -0,0 +1,115 @@
1
+ require_relative 'legacy_migration'
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module DevDoc
6
+ module Migration
7
+ # Never opt a reference out of its default index: `index: false` on
8
+ # `belongs_to` / `references` / `add_reference` is banned.
9
+ #
10
+ # ## Rationale
11
+ # Rails has indexed references by default since 5.0, so a reference
12
+ # column carries an index unless the migration explicitly opts out.
13
+ # The usual reason to opt out is a composite index whose leading
14
+ # column is the foreign key — the composite serves FK lookups too —
15
+ # but that dependency is invisible and fragile: a later migration can
16
+ # drop the composite, reorder its columns, or convert it to a partial
17
+ # or non-btree index, and nothing in that migration says a reference
18
+ # depends on it. The FK is silently unindexed from then on.
19
+ #
20
+ # An unindexed foreign key fails far from its cause: PostgreSQL
21
+ # enforces the constraint from the parent side as well, so every
22
+ # DELETE of a parent row runs a lookup against the child table — a
23
+ # sequential scan per deleted row when the column has no index. The
24
+ # cost surfaces in a console prune or a bulk cleanup years later,
25
+ # not at write time. InnoDB creates the index with the constraint;
26
+ # PostgreSQL, like SQL Server, leaves the referencing-side index to
27
+ # the application, so this cop does it.
28
+ #
29
+ # Keeping the default single-column index also frees the composite:
30
+ # with the FK covered on its own, a query-serving composite index may
31
+ # be dropped, reordered, or rebuilt without a hidden victim.
32
+ #
33
+ # ❌ Fragile — the composite is the FK's only index
34
+ # create_table :readings do |t|
35
+ # t.belongs_to :sensor, foreign_key: true, null: false, index: false
36
+ # end
37
+ # add_index :readings, %i[sensor_id recorded_at], unique: true
38
+ #
39
+ # ✔️ The FK keeps its own index; the composite serves queries
40
+ # create_table :readings do |t|
41
+ # t.belongs_to :sensor, foreign_key: true, null: false
42
+ # end
43
+ # add_index :readings, %i[sensor_id recorded_at], unique: true
44
+ #
45
+ # ✔️ A hash customizes the index, it does not remove it
46
+ # t.belongs_to :parent, foreign_key: true, null: false, index: { unique: true }
47
+ #
48
+ # ## Exception
49
+ # None in ordinary code. Where a table's write volume genuinely
50
+ # cannot carry the extra index, keep `index: false` and disable this
51
+ # cop inline with a brief reason — and note in the same comment that
52
+ # the covering composite index is load-bearing for the FK, so later
53
+ # migrations do not reorder or drop it in good faith.
54
+ #
55
+ # NOTE: Migrations declared `< ActiveRecord::Migration[4.2]` are
56
+ # skipped entirely: the 4.2 compatibility layer flips the reference
57
+ # default to `index: false`, so the reference is unindexed whether
58
+ # or not the option is written — and fixing that would require the
59
+ # load-bearing `index: true`, not the removal of `index: false`.
60
+ #
61
+ # NOTE: This cop holds the index; the sibling cops
62
+ # `DevDoc/Migration/RequireReferenceForeignKey` and
63
+ # `DevDoc/Migration/ExplicitNullOnReference` require the constraint
64
+ # and the optionality to be stated, and
65
+ # `DevDoc/Migration/RedundantReferenceIndex` strips the redundant
66
+ # `index: true`. Together: everything written on a reference is a
67
+ # decision, everything omitted is doctrine — and the index is not a
68
+ # decision.
69
+ #
70
+ # @example
71
+ # # bad
72
+ # t.belongs_to :sensor, foreign_key: true, null: false, index: false
73
+ #
74
+ # # good
75
+ # t.belongs_to :sensor, foreign_key: true, null: false
76
+ #
77
+ # # good (customized, not removed)
78
+ # t.belongs_to :parent, foreign_key: true, index: { unique: true }
79
+ class RequireReferenceIndex < Base
80
+ include LegacyMigration
81
+
82
+ MSG = 'Remove `%<source>s` — the reference must keep its own index; a deliberate ' \
83
+ 'exception keeps the option plus a reasoned disable of this cop.'.freeze
84
+
85
+ RESTRICT_ON_SEND = %i[belongs_to references add_reference add_belongs_to].freeze
86
+
87
+ def on_send(node)
88
+ return if legacy_migration?(node)
89
+
90
+ options = node.arguments.find(&:hash_type?)
91
+ return unless options
92
+
93
+ options.pairs.each do |pair|
94
+ add_offense(pair, message: format(MSG, source: pair.source)) if index_opt_out?(pair)
95
+ end
96
+ end
97
+
98
+ private
99
+
100
+ # `index: nil` opts out exactly like `index: false` (Rails checks
101
+ # the option's truthiness), so both literal falsy spellings flag.
102
+ # A hash value (`index: { unique: true }`) customizes the index
103
+ # rather than removing it, and `index: true` is redundant but
104
+ # harmless — RedundantReferenceIndex's domain, not this cop's.
105
+ def index_opt_out?(pair)
106
+ key = pair.key
107
+ return false unless (key.sym_type? || key.str_type?) && key.value.to_s == 'index'
108
+
109
+ pair.value.false_type? || pair.value.nil_type?
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
@@ -7,8 +7,28 @@ module RuboCop
7
7
  # ## Rationale
8
8
  # Avoid bypassing validation unless absolutely necessary. Methods like
9
9
  # `update_column`, `update_all`, `insert_all`, `upsert_all`, `delete_all`,
10
- # and `save(validate: false)` skip validations and callbacks, which hides
11
- # data integrity issues rather than surfacing them.
10
+ # and the `validate: false` option on `save`/`save!`/`create`/`create!`
11
+ # skip validations and callbacks, which hides data integrity issues
12
+ # rather than surfacing them. A validation refusal is INFORMATION: the
13
+ # record telling you its data is wrong — the response is to fix the
14
+ # data (backfill from what the ledger already knows), never to silence
15
+ # the gate (a real app, 2026-09-13: a `save!(validate: false)`
16
+ # membership write silenced the bank-account guard on legacy records;
17
+ # the cure was backfilling four purchases from their own transactions).
18
+ #
19
+ # ## Why bypasses are treated as hostile
20
+ # The guards that matter most are the ones the call site cannot see:
21
+ # same-account references, direction/state alignment, finalize gates.
22
+ # A bypassing write does not fail those guards — it never consults
23
+ # them, so their failure ships silently into the data (real case:
24
+ # a real app's `move_to`, 2026-09-12, relocated purchase items
25
+ # across accounts while their category references stayed behind —
26
+ # invisible to the suite, caught only by a manual audit).
27
+ #
28
+ # That is why the sanctioned disable protocol asks for more than a
29
+ # reason: name the COLUMNS being written and why record-by-record
30
+ # (`find_each` + `save!`) is not viable — a reviewer must be able to
31
+ # check the blast radius, not just the intent.
12
32
  #
13
33
  # Even in migrations, check the code to see if there is any blatant
14
34
  # reason why existing records may be invalid. If there is, fix those
@@ -16,8 +36,9 @@ module RuboCop
16
36
  #
17
37
  # ## Relationship with Rails/SkipsModelValidations
18
38
  # This cop is a strict SUPERSET of the stock `Rails/SkipsModelValidations`
19
- # (it covers every method that cop flags, plus `delete_all` and
20
- # `save(validate: false)`), with per-method actionable messages instead
39
+ # (it covers every method that cop flags, plus `delete_all` and the
40
+ # `validate: false` option on save/save!/create/create!), with
41
+ # per-method actionable messages instead
21
42
  # of a generic one. Consumer projects should enable THIS cop and disable
22
43
  # `Rails/SkipsModelValidations` — running both forces every disable
23
44
  # comment to name two cops for the same offense. Methods that skip
@@ -44,6 +65,9 @@ module RuboCop
44
65
  # # bad
45
66
  # user.save(validate: false)
46
67
  #
68
+ # # bad — the bang adds raise-on-failure, NOT validations
69
+ # user.save!(validate: false)
70
+ #
47
71
  # # bad
48
72
  # User.insert_all(rows)
49
73
  #
@@ -53,22 +77,31 @@ module RuboCop
53
77
  # faq.save!
54
78
  # end
55
79
  class AvoidBypassingValidation < Base
80
+ # The core clause shared by the message family: WHY a bypass is
81
+ # hostile, not just what it skips. A bypass does not fail the
82
+ # model's integrity guards — it never consults them.
83
+ GUARD_CLAUSE = 'it bypasses validations AND callbacks, so every model-level integrity guard ' \
84
+ 'is silently inoperative for this write'.freeze
85
+ PROTOCOL = 'sanctioned bypasses: disable naming the COLUMNS written and why ' \
86
+ 'record-by-record is not viable (see cop doc)'.freeze
87
+
56
88
  MESSAGES = {
57
- update_column: 'Avoid `update_column`; it bypasses validations. Use `save!` instead.',
58
- update_columns: 'Avoid `update_columns`; it bypasses validations. Use `save!` instead.',
59
- update_attribute: 'Avoid `update_attribute`; it bypasses validations (the singular is not ' \
89
+ update_column: "Avoid `update_column`; #{GUARD_CLAUSE}. Use `update!` instead.",
90
+ update_columns: "Avoid `update_columns`; #{GUARD_CLAUSE}. Use `update!` instead.",
91
+ update_attribute: "Avoid `update_attribute`; #{GUARD_CLAUSE} (the singular is not " \
60
92
  'a validating `update`). Use `update!` instead.',
61
- update_all: 'Avoid `update_all`; it bypasses validations. Use `save!` in a loop instead.',
62
- insert: 'Avoid `insert`; it bypasses validations. Use `create!` instead, ' \
63
- 'or `# rubocop:disable` with a reason if a raw insert is intentional.',
93
+ update_all: "Avoid `update_all`; #{GUARD_CLAUSE} for every matched row. " \
94
+ 'Use `save!` in a loop instead.',
95
+ insert: "Avoid `insert`; #{GUARD_CLAUSE}. Use `create!` instead, " \
96
+ "or #{PROTOCOL} if a raw insert is intentional.",
64
97
  insert!: 'Avoid `insert!`; it bypasses validations (the bang is about duplicate keys, ' \
65
98
  'not validity). Use `create!` instead.',
66
- insert_all: 'Avoid `insert_all`; it bypasses validations. Use `create!` in a loop, ' \
67
- 'or `# rubocop:disable` with a reason if bulk-insert is intentional.',
68
- upsert: 'Avoid `upsert`; it bypasses validations. Use `create!`/`update!` instead, ' \
69
- 'or `# rubocop:disable` with a reason if a raw upsert is intentional.',
70
- upsert_all: 'Avoid `upsert_all`; it bypasses validations. Use `create!`/`update!` in a loop, ' \
71
- 'or `# rubocop:disable` with a reason if bulk-upsert is intentional.',
99
+ insert_all: "Avoid `insert_all`; #{GUARD_CLAUSE} for every row. Use `create!` in a loop, " \
100
+ "or #{PROTOCOL} if bulk-insert is intentional.",
101
+ upsert: "Avoid `upsert`; #{GUARD_CLAUSE}. Use `create!`/`update!` instead, " \
102
+ "or #{PROTOCOL} if a raw upsert is intentional.",
103
+ upsert_all: "Avoid `upsert_all`; #{GUARD_CLAUSE} for every row. Use `create!`/`update!` in a loop, " \
104
+ "or #{PROTOCOL} if bulk-upsert is intentional.",
72
105
  toggle!: 'Avoid `toggle!`; it saves without validations. Use `toggle(...).save!` instead.',
73
106
  increment!: 'Avoid `increment!`; it writes without validations. Use `increment(...).save!` instead.',
74
107
  decrement!: 'Avoid `decrement!`; it writes without validations. Use `decrement(...).save!` instead.',
@@ -85,18 +118,28 @@ module RuboCop
85
118
  '(`updated_at` updates automatically), or `AllowedMethods` if bare timestamp bumps are ' \
86
119
  'accepted in this project.',
87
120
  touch_all: 'Avoid `touch_all`; it issues a bulk UPDATE that bypasses validations and callbacks. ' \
88
- 'Iterate with `save!`, or `# rubocop:disable` with a reason if a bulk timestamp bump ' \
89
- 'is intentional.',
121
+ "Iterate with `save!`, or #{PROTOCOL} if a bulk timestamp bump is intentional.",
90
122
  insert_all!: 'Avoid `insert_all!`; it bypasses validations (the bang is about duplicate keys, ' \
91
123
  'not validity). Use `create!` in a loop, or `# rubocop:disable` with a reason if ' \
92
124
  'bulk-insert is intentional.',
93
125
  delete_all: 'Avoid `delete_all`; it bypasses callbacks. Use `destroy_all` to run callbacks, ' \
94
- 'or `# rubocop:disable` with a reason if bulk-delete is intentional.'
126
+ "or #{PROTOCOL} if bulk-delete is intentional."
95
127
  }.freeze
96
128
 
97
- SAVE_MSG = 'Avoid `save(validate: false)`; it bypasses validations. Use `save!` instead.'.freeze
129
+ SAVE_MSG = 'Avoid `%<selector>s(validate: false)`; validations are the only thing it skips — if a ' \
130
+ 'guard refuses this save, that refusal is information: the record is telling you its ' \
131
+ 'data is wrong. Fix the data (backfill), not the gate.'.freeze
132
+
133
+ # save! matters as much as save: a bang only adds raise-on-failure,
134
+ # it does NOT restore validations — `save!(validate: false)` is the
135
+ # exact shape that slipped past this cop's pre-2026-09-13 `:save`-
136
+ # only RESTRICT_ON_SEND (a real app, purchase 29: a membership
137
+ # write silenced the bank-account guard on legacy data, and the
138
+ # suite + lint both waved it through). create/create! accept the
139
+ # same option with the same effect.
140
+ VALIDATION_GATE_METHODS = %i[save save! create create!].freeze
98
141
 
99
- RESTRICT_ON_SEND = (MESSAGES.keys + %i[save]).freeze
142
+ RESTRICT_ON_SEND = (MESSAGES.keys + VALIDATION_GATE_METHODS).freeze
100
143
 
101
144
  # insert/insert!/upsert are AR *class-level* APIs (User.insert(...)),
102
145
  # while `insert` on a non-const receiver is everyday Array#insert —
@@ -111,10 +154,8 @@ module RuboCop
111
154
  def on_send(node)
112
155
  return if allowed_methods.include?(node.method_name.to_s)
113
156
 
114
- if node.method?(:save)
115
- return unless save_with_validate_false?(node)
116
-
117
- add_offense(node.loc.selector, message: SAVE_MSG)
157
+ if VALIDATION_GATE_METHODS.include?(node.method_name)
158
+ validation_gate_offense(node)
118
159
  else
119
160
  return unless receiver_shape_matches?(node)
120
161
 
@@ -124,6 +165,17 @@ module RuboCop
124
165
 
125
166
  private
126
167
 
168
+ # save/save!/create/create!: only offensive WITH the skip option —
169
+ # the plain forms are the validating writes this cop pushes toward.
170
+ def validation_gate_offense(node)
171
+ return unless skips_validation_option?(node)
172
+
173
+ add_offense(
174
+ node.loc.selector,
175
+ message: format(SAVE_MSG, selector: node.method_name)
176
+ )
177
+ end
178
+
127
179
  def receiver_shape_matches?(node)
128
180
  const_receiver = node.receiver&.const_type?
129
181
  return const_receiver if CONST_RECEIVER_ONLY.include?(node.method_name)
@@ -139,7 +191,10 @@ module RuboCop
139
191
  cop_config.fetch('AllowedMethods', []).map(&:to_s)
140
192
  end
141
193
 
142
- def save_with_validate_false?(node)
194
+ # Only a literal `validate: false` option is detected; a dynamic
195
+ # value (`validate: skip`) escapes this cop — deliberate trade to
196
+ # avoid false positives on non-AR objects.
197
+ def skips_validation_option?(node)
143
198
  node.arguments.any? do |arg|
144
199
  next unless arg.hash_type?
145
200
 
@@ -98,7 +98,7 @@ module RuboCop
98
98
  private
99
99
 
100
100
  def flagged_methods
101
- @flagged_methods ||= Array(cop_config['Methods'] || DEFAULT_METHODS).map(&:to_sym)
101
+ @flagged_methods ||= Array(cop_config['Methods'] || DEFAULT_METHODS).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
102
102
  end
103
103
  end
104
104
  end