rubocop-dev_doc 0.18.0 → 0.20.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 +4 -4
- data/config/default.yml +184 -2
- data/lib/dev_doc/i18n/pseudo_locale.rb +1 -1
- data/lib/dev_doc/test/lints/cross_tenant_canary_check.rb +1 -1
- data/lib/dev_doc/test/lints/cross_tenant_canary_sweep.rb +6 -3
- data/lib/dev_doc/test/lints/http_driven_controller_tests.rb +2 -0
- data/lib/dev_doc/test/lints/no_file_excludes.rb +1 -1
- data/lib/dev_doc/test/pseudo_i18n_crawler.rb +4 -0
- data/lib/rubocop/cop/dev_doc/auth/adjacent_justification.rb +44 -7
- data/lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb +2 -2
- data/lib/rubocop/cop/dev_doc/auth/login_only_policy_justification.rb +1 -1
- data/lib/rubocop/cop/dev_doc/auth/unscoped_find_justification.rb +2 -2
- data/lib/rubocop/cop/dev_doc/bundler/conflicting_gem.rb +74 -0
- data/lib/rubocop/cop/dev_doc/exception_class_list.rb +32 -0
- data/lib/rubocop/cop/dev_doc/i18n/translation_key_prefix.rb +1 -1
- data/lib/rubocop/cop/dev_doc/migration/legacy_migration.rb +26 -0
- data/lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb +5 -15
- data/lib/rubocop/cop/dev_doc/migration/require_reference_index.rb +115 -0
- data/lib/rubocop/cop/dev_doc/rails/avoid_lifecycle_method_override.rb +1 -1
- data/lib/rubocop/cop/dev_doc/rails/create_or_find_by.rb +66 -0
- data/lib/rubocop/cop/dev_doc/rails/find_or_create_by_justification.rb +106 -0
- data/lib/rubocop/cop/dev_doc/rails/no_error_message_comparison.rb +178 -0
- data/lib/rubocop/cop/dev_doc/rails/no_form_param_lookup_in_controller.rb +1 -1
- data/lib/rubocop/cop/dev_doc/rails/rescue_record_not_unique_index.rb +212 -0
- data/lib/rubocop/cop/dev_doc/rails/unique_index_backing.rb +205 -0
- data/lib/rubocop/cop/dev_doc/style/avoid_kernel_array.rb +103 -0
- data/lib/rubocop/cop/dev_doc/style/no_silent_rescue.rb +36 -26
- data/lib/rubocop/cop/dev_doc/style/no_unscoped_method_definitions.rb +1 -1
- data/lib/rubocop/cop/dev_doc/style/rescue_justification.rb +330 -0
- data/lib/rubocop/cop/dev_doc/test/justification_covers.rb +216 -0
- data/lib/rubocop/cop/dev_doc/test/justification_header.rb +86 -5
- data/lib/rubocop/cop/dev_doc/test/require_job_invocation_in_job_tests.rb +154 -0
- data/lib/rubocop/cop/dev_doc/test/require_unit_test_justification.rb +5 -24
- data/lib/rubocop/cop/dev_doc/test/test_file_placement.rb +30 -2
- data/lib/rubocop/dev_doc/version.rb +1 -1
- metadata +16 -3
|
@@ -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
|
-
#
|
|
18
|
-
#
|
|
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
|
|
@@ -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
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
module RuboCop
|
|
2
|
+
module Cop
|
|
3
|
+
module DevDoc
|
|
4
|
+
module Rails
|
|
5
|
+
# `create_or_find_by` / `create_or_find_by!` are banned; uniqueness
|
|
6
|
+
# writes follow the two rules of 03_model.md item 14 instead.
|
|
7
|
+
#
|
|
8
|
+
# ## Rationale
|
|
9
|
+
# `create_or_find_by` looks like the safe default for a
|
|
10
|
+
# unique-constrained row, but it is only correct under preconditions
|
|
11
|
+
# that are the exception, not the rule: a FULL non-partial unique
|
|
12
|
+
# index over EXACTLY the passed attributes (a partial or wider index
|
|
13
|
+
# lets the INSERT succeed where the method assumed it would conflict),
|
|
14
|
+
# literal attributes, and no uniqueness validation sabotaging the
|
|
15
|
+
# INSERT (Rails tries the validation first, so a scope the index does
|
|
16
|
+
# not share turns the race into `RecordInvalid` instead of the
|
|
17
|
+
# re-fetch path). Soft-deletable models under a plain unique index
|
|
18
|
+
# break it further: the conflict re-fetch uses the default scope, so
|
|
19
|
+
# a soft-deleted winner turns the method into `nil`/`RecordNotFound`.
|
|
20
|
+
#
|
|
21
|
+
# The two rules that replace it (03_model.md item 14): rule 2, the
|
|
22
|
+
# default — the unique index is the arbiter (`transaction(requires_new:
|
|
23
|
+
# true)` around the write, `rescue ActiveRecord::RecordNotUnique`, the
|
|
24
|
+
# rescue body states what losing the race means; policed by
|
|
25
|
+
# `DevDoc/Rails/RescueRecordNotUniqueIndex`); rule 1, the exception —
|
|
26
|
+
# `find_or_create_by` only when no unique index is possible and a rare
|
|
27
|
+
# duplicate is tolerable, stated in an adjacent justification comment
|
|
28
|
+
# (policed by `DevDoc/Rails/FindOrCreateByJustification`). Total
|
|
29
|
+
# enforcement, zero judgment: the method name itself is the offense.
|
|
30
|
+
#
|
|
31
|
+
# @example
|
|
32
|
+
# # bad
|
|
33
|
+
# Membership.create_or_find_by!(member: m, group: g)
|
|
34
|
+
#
|
|
35
|
+
# # good — rule 2: the index arbitrates, the rescue states the loss
|
|
36
|
+
# def self.add_member!(member, group)
|
|
37
|
+
# transaction(requires_new: true) do
|
|
38
|
+
# create!(member: member, group: group)
|
|
39
|
+
# end
|
|
40
|
+
# rescue ActiveRecord::RecordNotUnique
|
|
41
|
+
# # Lost the (group, member) race: the winner's row is the same membership.
|
|
42
|
+
# find_by!(member: member, group: group)
|
|
43
|
+
# end
|
|
44
|
+
#
|
|
45
|
+
# # good — rule 1 (only where no index is possible; comment required)
|
|
46
|
+
# # unique-write: no index possible here because ...; a rare duplicate is tolerable because ...
|
|
47
|
+
# Widget.find_or_create_by!(token: token)
|
|
48
|
+
class CreateOrFindBy < Base
|
|
49
|
+
MSG = '`create_or_find_by%<bang>s` is banned: its preconditions (a full, non-partial unique ' \
|
|
50
|
+
'index over exactly the passed attributes, literal attributes, no uniqueness ' \
|
|
51
|
+
'validation on the INSERT path) are the exception, not the rule. Use the two rules ' \
|
|
52
|
+
'of 03_model.md item 14 instead: the index as arbiter (rule 2) or a justified ' \
|
|
53
|
+
'find_or_create_by (rule 1).'.freeze
|
|
54
|
+
|
|
55
|
+
RESTRICT_ON_SEND = %i[create_or_find_by create_or_find_by!].freeze
|
|
56
|
+
|
|
57
|
+
def on_send(node)
|
|
58
|
+
add_offense(node.loc.selector, message: format(MSG, bang: node.method_name.to_s.end_with?('!') ? '!' : ''))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
alias on_csend on_send
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
require_relative 'unique_index_backing'
|
|
2
|
+
|
|
3
|
+
module RuboCop
|
|
4
|
+
module Cop
|
|
5
|
+
module DevDoc
|
|
6
|
+
module Rails
|
|
7
|
+
# Rule 1 of 03_model.md item 14: `find_or_create_by` is the rare
|
|
8
|
+
# exception for unique-constrained rows and must carry an adjacent
|
|
9
|
+
# justification comment; when a unique index already backs the
|
|
10
|
+
# written attributes, the site is rule 2 instead (the index is the
|
|
11
|
+
# arbiter — attempt, rescue, state the loss).
|
|
12
|
+
#
|
|
13
|
+
# ## Rationale
|
|
14
|
+
# `find_or_create_by` is SELECT-first, so under a race both callers
|
|
15
|
+
# see "not found" and both INSERT; without a rescue one of them
|
|
16
|
+
# 500s. The two-rules standard (03_model.md item 14) therefore makes
|
|
17
|
+
# the index-arbiter shape the default and keeps `find_or_create_by`
|
|
18
|
+
# only where NO unique index is possible and a rare duplicate (or a
|
|
19
|
+
# rescued conflict) is tolerable — a claim the author must state
|
|
20
|
+
# where a reviewer reads it, in an adjacent `unique-write:` comment.
|
|
21
|
+
#
|
|
22
|
+
# Strict mode (on by default) reads the schema: literal attribute
|
|
23
|
+
# keys on a CONSTANT receiver that resolve to a covering unique
|
|
24
|
+
# index produce a different offense — the justification, whatever it
|
|
25
|
+
# says, is factually wrong there, because an index exists and rule 2
|
|
26
|
+
# applies. Sites whose attributes do not resolve (dynamic hashes,
|
|
27
|
+
# association receivers) are silently skipped by strict mode and
|
|
28
|
+
# judged only on the comment.
|
|
29
|
+
#
|
|
30
|
+
# `DevDoc/Rails/CreateOrFindBy` bans the `create_or_find_by` family
|
|
31
|
+
# separately (total enforcement, no justification escapes it).
|
|
32
|
+
#
|
|
33
|
+
# ## Configuration
|
|
34
|
+
# `JustificationMarker` (default: `unique-write:`) — accepted
|
|
35
|
+
# trailing on the flagged line or in the contiguous comment block
|
|
36
|
+
# ending on the line directly above it (the shared
|
|
37
|
+
# adjacent-justification contract). `Strict` (default: true) —
|
|
38
|
+
# enable the schema-backed "this should be rule 2" pass.
|
|
39
|
+
#
|
|
40
|
+
# @example
|
|
41
|
+
# # bad — no stated reason for the rule-1 exception
|
|
42
|
+
# Widget.find_or_create_by!(token: token)
|
|
43
|
+
#
|
|
44
|
+
# # good — rule 1, justified
|
|
45
|
+
# # unique-write: tokens are recycled weekly with no stable key to index; a rare
|
|
46
|
+
# # duplicate pair is merged by the nightly sweep
|
|
47
|
+
# Widget.find_or_create_by!(token: token)
|
|
48
|
+
#
|
|
49
|
+
# # bad (strict) — an index covers these columns; this is rule 2
|
|
50
|
+
# Widget.find_or_create_by!(token: token) # index_widgets_on_token exists
|
|
51
|
+
class FindOrCreateByJustification < Base
|
|
52
|
+
include Auth::AdjacentJustification
|
|
53
|
+
include UniqueIndexBacking
|
|
54
|
+
|
|
55
|
+
MSG = '`find_or_create_by%<bang>s` is the rule-1 exception of 03_model.md item 14 and needs an ' \
|
|
56
|
+
'adjacent "%<marker>s <why>" comment stating why no unique index is possible here and why a ' \
|
|
57
|
+
'rare duplicate is tolerable.'.freeze
|
|
58
|
+
STRICT_MSG = 'A unique index (%<index>s) covers these attributes — this write is rule 2 of ' \
|
|
59
|
+
'03_model.md item 14: attempt the write inside `transaction(requires_new: true)`, rescue ' \
|
|
60
|
+
'`ActiveRecord::RecordNotUnique`, and state what losing the race means. (No comment ' \
|
|
61
|
+
'saves it: the justification would be factually wrong.)'.freeze
|
|
62
|
+
|
|
63
|
+
RESTRICT_ON_SEND = %i[find_or_create_by find_or_create_by!].freeze
|
|
64
|
+
|
|
65
|
+
def on_send(node)
|
|
66
|
+
if (index = strict_offending_index(node))
|
|
67
|
+
add_offense(node.loc.selector, message: format(STRICT_MSG, index: index.name))
|
|
68
|
+
elsif !adjacent_justification?(node)
|
|
69
|
+
add_offense(node.loc.selector, message: missing_justification_message(node))
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
alias on_csend on_send
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
# The covering unique index when strict mode is on, the write's
|
|
78
|
+
# attributes are a literal hash, and a CONSTANT receiver names the
|
|
79
|
+
# table — nil otherwise (silent skip, per the cop's doc).
|
|
80
|
+
def strict_offending_index(node)
|
|
81
|
+
return nil unless strict? && node.receiver&.const_type?
|
|
82
|
+
|
|
83
|
+
keys = write_attribute_keys(node)
|
|
84
|
+
return nil unless keys
|
|
85
|
+
|
|
86
|
+
table = receiver_table(node.receiver)
|
|
87
|
+
covering_unique_index(table: table, attribute_keys: keys)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def strict?
|
|
91
|
+
cop_config.fetch('Strict', true)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def missing_justification_message(node)
|
|
95
|
+
bang = node.method_name.to_s.end_with?('!') ? '!' : ''
|
|
96
|
+
format(MSG, bang: bang, marker: justification_marker)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def justification_marker
|
|
100
|
+
cop_config.fetch('JustificationMarker', 'unique-write:')
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
module RuboCop
|
|
2
|
+
module Cop
|
|
3
|
+
module DevDoc
|
|
4
|
+
module Rails
|
|
5
|
+
# Do not branch on the TEXT of an ActiveModel error message; add the
|
|
6
|
+
# error with a symbol type and branch on the type.
|
|
7
|
+
#
|
|
8
|
+
# ## Rationale
|
|
9
|
+
# The compared text is written in two places — the `errors.add` that
|
|
10
|
+
# produces it and the branch that matches it — and only both copies
|
|
11
|
+
# staying identical keeps the branch alive. Rewording the message,
|
|
12
|
+
# translating it, or a second error joining it on the record silently
|
|
13
|
+
# sends the branch down its generic path; no test notices, because
|
|
14
|
+
# the test asserts the same text. A symbol-typed error has no text to
|
|
15
|
+
# drift: the branch asks the record which KIND of failure it holds.
|
|
16
|
+
#
|
|
17
|
+
# ❌ `errors.add(:base, 'Article is already published')` in the model,
|
|
18
|
+
# `errors.full_messages == ['Article is already published']` in the
|
|
19
|
+
# caller
|
|
20
|
+
# ✔️ `errors.add(:base, :already_published, message: 'Article is
|
|
21
|
+
# already published')` in the model,
|
|
22
|
+
# `errors.of_kind?(:base, :already_published)` in the caller
|
|
23
|
+
#
|
|
24
|
+
# Both legs of the ratchet: observed in a PR under review
|
|
25
|
+
# (2026-11-13, session 27c64a62); measured over the `app/` and
|
|
26
|
+
# `lib/` trees of 13 consuming codebases (9,859 files) — the
|
|
27
|
+
# full_messages family fired zero times, the `errors[]`/`messages`
|
|
28
|
+
# family once, a true positive whose fix is `errors.added?`. The
|
|
29
|
+
# finished cop re-measured over the same apps' `app/` trees: one
|
|
30
|
+
# offense, the same line.
|
|
31
|
+
#
|
|
32
|
+
# ## Exception
|
|
33
|
+
# A genuinely external string the code cannot type — an `errors`
|
|
34
|
+
# object handed over by an API client whose messages are fixed
|
|
35
|
+
# upstream — is not yours to symbol-type. Disable inline, naming the
|
|
36
|
+
# source:
|
|
37
|
+
#
|
|
38
|
+
# # rubocop:disable DevDoc/Rails/NoErrorMessageComparison
|
|
39
|
+
# # -- matches the upstream API's fixed error text
|
|
40
|
+
#
|
|
41
|
+
# NOTE: Blindness, for reviewers: a message stored in a variable
|
|
42
|
+
# before the comparison is not seen; a comparison inside a helper
|
|
43
|
+
# method (the messages arrive as a parameter) is not seen; a
|
|
44
|
+
# comparison inside a block over the messages
|
|
45
|
+
# (`errors.full_messages.any? { |m| m.include?('taken') }`) is not
|
|
46
|
+
# seen — the receiver-chain walk never reaches a block argument; the
|
|
47
|
+
# Rails 6.1 error-object spellings (`errors.first.message`,
|
|
48
|
+
# `errors.where(:email).first.message`, `errors.map(&:message)`,
|
|
49
|
+
# `errors.full_message`) are not seen; an emptiness check
|
|
50
|
+
# (`errors.full_messages == []`) is not flagged — `errors.empty?` is
|
|
51
|
+
# that check's remedy, not this cop; a hash literal on the
|
|
52
|
+
# comparison side (`errors.messages == { email: [...] }`) is not
|
|
53
|
+
# seen — the literal side is a closed list of the observed shapes,
|
|
54
|
+
# and this spelling was never observed; `e.message` and
|
|
55
|
+
# `e.full_message` on exceptions are out of scope (measured mostly
|
|
56
|
+
# legitimate); and paths outside `app/` are not checked.
|
|
57
|
+
#
|
|
58
|
+
# @example
|
|
59
|
+
# # bad
|
|
60
|
+
# if @article.errors.full_messages == ['Article is already published']
|
|
61
|
+
# if @article.errors[:base].include?('Article is already published')
|
|
62
|
+
# case @article.errors.full_messages.first
|
|
63
|
+
# when 'Article is already published' then ...
|
|
64
|
+
# end
|
|
65
|
+
#
|
|
66
|
+
# # good
|
|
67
|
+
# @article.errors.add(:base, :already_published) # model
|
|
68
|
+
# if @article.errors.of_kind?(:base, :already_published) # caller
|
|
69
|
+
class NoErrorMessageComparison < Base
|
|
70
|
+
MSG = 'Branching on error message text breaks when the text changes or another error is added. ' \
|
|
71
|
+
'Add the error with a symbol type and check it with `errors.of_kind?` / `errors.added?`.'.freeze
|
|
72
|
+
|
|
73
|
+
RESTRICT_ON_SEND = %i[== != eql? equal? === include? match? match =~ !~
|
|
74
|
+
start_with? end_with? grep grep_v].freeze
|
|
75
|
+
|
|
76
|
+
# ActiveModel-specific names: any receiver chain containing one is
|
|
77
|
+
# an error read. (`full_message` is NOT here: `Exception#full_message`
|
|
78
|
+
# is core Ruby, so the any-receiver rule would flag exception
|
|
79
|
+
# comparisons that are out of scope; the ActiveModel/Error-object
|
|
80
|
+
# spellings are a NOTE blind spot instead.)
|
|
81
|
+
FULL_MESSAGE_METHODS = %i[full_messages full_messages_for].freeze
|
|
82
|
+
# These count only when the chain resolves to an `errors` call, so
|
|
83
|
+
# `conversation.messages` and `params[:errors]` stay silent.
|
|
84
|
+
ERRORS_METHODS = %i[to_a messages messages_for []].freeze
|
|
85
|
+
|
|
86
|
+
def on_send(node)
|
|
87
|
+
flag_comparison(node, [node.receiver, *node.arguments])
|
|
88
|
+
end
|
|
89
|
+
# Safe navigation (`messages&.include?('text')`) parses as csend
|
|
90
|
+
# nodes, which on_send does not receive — alias it so `&.` is
|
|
91
|
+
# caught too.
|
|
92
|
+
alias on_csend on_send
|
|
93
|
+
|
|
94
|
+
# `/text/ =~ errors.full_messages.first` parses as its own node
|
|
95
|
+
# type (the match-assignment idiom), not a send.
|
|
96
|
+
def on_match_with_lvasgn(node)
|
|
97
|
+
flag_comparison(node, node.children)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def on_case(node)
|
|
101
|
+
subject = node.condition
|
|
102
|
+
return unless error_read?(subject)
|
|
103
|
+
return unless node.when_branches.any? do |when_node|
|
|
104
|
+
when_node.conditions.any? { |condition| literalish?(condition) }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
add_offense(subject)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
private
|
|
111
|
+
|
|
112
|
+
# Offense when at least one operand is an error read (below) and
|
|
113
|
+
# at least one other is literal-ish (below).
|
|
114
|
+
def flag_comparison(node, operands)
|
|
115
|
+
error_reads, others = operands.compact.partition { |operand| error_read?(operand) }
|
|
116
|
+
return if error_reads.empty?
|
|
117
|
+
return unless others.any? { |operand| literalish?(operand) }
|
|
118
|
+
|
|
119
|
+
add_offense(node)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# An operand reads error message text when a node in its receiver
|
|
123
|
+
# chain is a full-message reader (any receiver — the names are
|
|
124
|
+
# ActiveModel-specific), or one of ERRORS_METHODS whose receiver is
|
|
125
|
+
# an `errors` call.
|
|
126
|
+
def error_read?(node)
|
|
127
|
+
return false unless call_node?(node)
|
|
128
|
+
|
|
129
|
+
if FULL_MESSAGE_METHODS.include?(node.method_name) ||
|
|
130
|
+
(ERRORS_METHODS.include?(node.method_name) && errors_call?(node.receiver))
|
|
131
|
+
true
|
|
132
|
+
else
|
|
133
|
+
error_read?(node.receiver)
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# An `errors` call, or a local/ivar assigned from one (`errors =
|
|
138
|
+
# record.errors; errors[:email]...`) — the assignment idiom the
|
|
139
|
+
# observed PR used. A non-ActiveModel object named `errors` trips
|
|
140
|
+
# this too; that is the inline-disable case.
|
|
141
|
+
def errors_call?(node)
|
|
142
|
+
return false unless node
|
|
143
|
+
|
|
144
|
+
if %i[send csend].include?(node.type)
|
|
145
|
+
node.method_name == :errors
|
|
146
|
+
elsif node.type == :lvar
|
|
147
|
+
node.children.first == :errors
|
|
148
|
+
elsif node.type == :ivar
|
|
149
|
+
node.children.first == :@errors
|
|
150
|
+
else
|
|
151
|
+
false
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def call_node?(node)
|
|
156
|
+
%i[send csend].include?(node&.type)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# The literal side of the observed comparisons (inclusion-based
|
|
160
|
+
# detection): string-ish literals, a regexp, a constant (which only
|
|
161
|
+
# moves the text), a `t(...)` / `translate(...)` call (branching on
|
|
162
|
+
# translated text is the same smell plus a locale dependency), and
|
|
163
|
+
# a NON-EMPTY array of those (an empty array is an emptiness check
|
|
164
|
+
# — `errors.full_messages == []` wants `errors.empty?`, not this
|
|
165
|
+
# cop's message). A variable or method call is not flagged.
|
|
166
|
+
def literalish?(node)
|
|
167
|
+
case node&.type
|
|
168
|
+
when :str, :dstr, :regexp, :const then true
|
|
169
|
+
when :send, :csend then %i[t translate].include?(node.method_name)
|
|
170
|
+
when :array then node.children.any? && node.children.all? { |element| literalish?(element) }
|
|
171
|
+
else false
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
end
|
|
@@ -223,7 +223,7 @@ module RuboCop
|
|
|
223
223
|
end
|
|
224
224
|
|
|
225
225
|
def finder_methods
|
|
226
|
-
@finder_methods ||= Array(cop_config.fetch('FinderMethods', %w[find find_by find_by!])).map(&:to_sym)
|
|
226
|
+
@finder_methods ||= Array(cop_config.fetch('FinderMethods', %w[find find_by find_by!])).map(&:to_sym) # rubocop:disable DevDoc/Style/AvoidKernelArray -- cop config accepts one method name or a list
|
|
227
227
|
end
|
|
228
228
|
|
|
229
229
|
def justification_marker
|