rubocop-munra 0.2.0 → 1.0.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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -0
  3. data/README.md +11 -1
  4. data/config/default.yml +101 -1
  5. data/lib/rubocop/cop/munra/00_model_scope_names.rb +42 -0
  6. data/lib/rubocop/cop/munra/00_model_spec_section_checks.rb +71 -0
  7. data/lib/rubocop/cop/munra/00_rspec_helpers.rb +26 -3
  8. data/lib/rubocop/cop/munra/00_transaction_block_mixin.rb +7 -6
  9. data/lib/rubocop/cop/munra/address_fields_order.rb +66 -0
  10. data/lib/rubocop/cop/munra/address_state_select.rb +3 -3
  11. data/lib/rubocop/cop/munra/admin_policy.rb +55 -8
  12. data/lib/rubocop/cop/munra/brazilian_state_inclusion.rb +67 -0
  13. data/lib/rubocop/cop/munra/builtin_validation_options.rb +24 -6
  14. data/lib/rubocop/cop/munra/digits_only_attributes.rb +103 -0
  15. data/lib/rubocop/cop/munra/email_format.rb +21 -26
  16. data/lib/rubocop/cop/munra/flash_success_locale_name.rb +30 -25
  17. data/lib/rubocop/cop/munra/flash_success_name.rb +2 -2
  18. data/lib/rubocop/cop/munra/full_error_messages.rb +3 -6
  19. data/lib/rubocop/cop/munra/let_layout.rb +9 -2
  20. data/lib/rubocop/cop/munra/literal_expectation.rb +68 -0
  21. data/lib/rubocop/cop/munra/model_spec_structure.rb +156 -0
  22. data/lib/rubocop/cop/munra/named_subject_layout.rb +4 -6
  23. data/lib/rubocop/cop/munra/no_current_date_in_system_spec.rb +37 -0
  24. data/lib/rubocop/cop/munra/no_human_attribute_name.rb +1 -1
  25. data/lib/rubocop/cop/munra/no_inline_validation.rb +1 -1
  26. data/lib/rubocop/cop/munra/no_leading_dot.rb +1 -1
  27. data/lib/rubocop/cop/munra/no_mixed_example_siblings.rb +57 -0
  28. data/lib/rubocop/cop/munra/no_shared_examples.rb +9 -4
  29. data/lib/rubocop/cop/munra/one_example_per_context.rb +54 -0
  30. data/lib/rubocop/cop/munra/policy_blank_deny.rb +133 -0
  31. data/lib/rubocop/cop/munra/service_object.rb +14 -6
  32. data/lib/rubocop/cop/munra/validations_before_callbacks.rb +80 -0
  33. data/lib/rubocop/munra/plugin.rb +1 -1
  34. data/lib/rubocop/munra/version.rb +1 -3
  35. metadata +14 -19
  36. data/.github/workflows/ci.yml +0 -29
  37. data/.github/workflows/docs.yml +0 -90
  38. data/.ruby-version +0 -1
  39. data/AGENTS.md +0 -101
  40. data/CODE_OF_CONDUCT.md +0 -10
  41. data/Rakefile +0 -42
  42. data/antora-playbook.yml +0 -22
  43. data/docs/antora.yml +0 -5
  44. data/docs/modules/ROOT/nav.adoc +0 -5
  45. data/docs/modules/ROOT/pages/cops.adoc +0 -2
  46. data/docs/modules/ROOT/pages/cops_munra.adoc +0 -1026
  47. data/docs/modules/ROOT/pages/index.adoc +0 -11
  48. data/docs/modules/ROOT/pages/installation.adoc +0 -50
  49. data/docs/modules/ROOT/pages/usage.adoc +0 -98
  50. data/docs/usage.md +0 -29
  51. data/package-lock.json +0 -1930
  52. data/package.json +0 -12
  53. data/sig/rubocop/munra.rbs +0 -6
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c2ff80bee992f61e93093a6140134013110cdda8fc4fbaab377987cd0b4dcb7f
4
- data.tar.gz: 5d89620ccec1444e05a366361e4377858c7c2d7bf975706848781fa9f34145d7
3
+ metadata.gz: 43c89fdb85e487281bbce718bfabcb5191883a1636b16b4d6d5543a740a07873
4
+ data.tar.gz: ad7d3ccba1b872a9dd727961a0be4bf0d9677d91c3e87ee2aac95ec18c55c0b0
5
5
  SHA512:
6
- metadata.gz: 321b8da764f82ff08b59d48788790e37751caa2b4f68691e634c6e1839f75790d13f274a040925bc2234d20941399b52760c283b637ee6df35c06ec4cafa307b
7
- data.tar.gz: 31919c3dc8ef5df183ce49f89d97cdecdc773d6ff9e7d7c3850490dd487880131cdeed8fb2c168ae26826498fe45207e055b6aa6371588771ef642cd21a7a56c
6
+ metadata.gz: 8f35a81e466c18aa7a9efc8c9574355ed23ea5a57ae6e703346126afa4fdcac0b32346944f0357fa70029c0e904e18c985b3a30148bde72d12b64ad03c87f3e8
7
+ data.tar.gz: d1552a0d9d6b55fdee3ff84a07aba79710609d2d5395bd0335b8e28c9f8c09a280faa743b53d0e4b206752b45e334e9ac438727c4bc4cb9d8449fd5808148eae
data/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.0.0] - 2026-12-05
4
+
5
+ ### Added
6
+
7
+ - `Munra/AddressFieldsOrder`
8
+ - `Munra/BrazilianStateInclusion`
9
+ - `Munra/DigitsOnlyAttributes`
10
+ - `Munra/LiteralExpectation`
11
+ - `Munra/ModelSpecStructure`
12
+ - `Munra/NoCurrentDateInSystemSpec`
13
+ - `Munra/NoMixedExampleSiblings`
14
+ - `Munra/OneExamplePerContext`
15
+ - `Munra/PolicyBlankDeny`
16
+ - `Munra/ValidationsBeforeCallbacks`
17
+
18
+ ### Changed
19
+
20
+ - `Munra/AdminPolicy` recognizes `module Admin; class FooPolicy` and matches
21
+ `AllowedResolveFiles` against the relative path (not the basename alone).
22
+
23
+ ### Fixed
24
+
25
+ - `Munra/NoTransactionExit` recognizes local, ivar, `self`, and safe-navigation
26
+ receivers, plus `itblock` transaction bodies
27
+ - `Munra/AdminPolicy` matches `AllowedResolveFiles` against the project-relative
28
+ path when RuboCop inspects an absolute file path
29
+ - `Munra/ServiceObject` tracks `public` / `protected` after `private`, and skips
30
+ the configured service base class
31
+ - `Munra/DigitsOnlyAttributes` considers every symbol argument on `validates` and
32
+ `before_validation`
33
+ - `Munra/ValidationsBeforeCallbacks` treats `around_*`, commit, rollback, and
34
+ touch callbacks as ordering barriers
35
+ - `Munra/NoLeadingDot` autocorrect preserves `&.`
36
+ - `Munra/LiteralExpectation` and `Munra/NoSharedExamples` honor extra methods from
37
+ config (no fixed `RESTRICT_ON_SEND` filter)
38
+ - `Munra/AddressStateSelect` no longer matches `collection_select` /
39
+ `rich_text_field` as substring helpers
40
+ - `Munra/PolicyBlankDeny` flags `record.account_id&.blank?`
41
+ - `Munra/LetLayout` treats `{` / `do |args|` as block openers and `}` as a closer
42
+ - Quote YAML `on` in `Munra/BuiltinValidationOptions` so it is not loaded as `true`
43
+ - RSpec helpers recognize focused, pending, and `feature` aliases
44
+
3
45
  ## [0.2.0] - 2026-12-05
4
46
 
5
47
  ### Added
data/README.md CHANGED
@@ -41,30 +41,40 @@ Munra/ServiceObject:
41
41
 
42
42
  More configuration examples (`Include` / `Exclude`, department switches): [Usage](https://ramonsantos.github.io/rubocop-munra/rubocop-munra/usage.html).
43
43
 
44
- Per-cop reference (18 cops): [Munra cops](https://ramonsantos.github.io/rubocop-munra/rubocop-munra/cops_munra.html).
44
+ Per-cop reference (28 cops): [Munra cops](https://ramonsantos.github.io/rubocop-munra/rubocop-munra/cops_munra.html).
45
45
 
46
46
  ## Cops
47
47
 
48
48
  | Cop | Purpose |
49
49
  | --- | --- |
50
+ | `Munra/AddressFieldsOrder` | Address fields in views follow the configured order |
50
51
  | `Munra/AddressStateSelect` | Prefer configured state select helpers in ERB |
51
52
  | `Munra/AdminPolicy` | Admin policies inherit the configured base |
53
+ | `Munra/BrazilianStateInclusion` | State attributes validate inclusion in the configured constant |
52
54
  | `Munra/BuiltinValidationOptions` | Prefer `validates_with` over custom shorthand keys |
53
55
  | `Munra/CustomValidator` | Custom validators inherit `ActiveModel::Validator` |
56
+ | `Munra/DigitsOnlyAttributes` | Digit attributes use the configured normalizer |
54
57
  | `Munra/EmailFormat` | Email attributes use the configured validator |
55
58
  | `Munra/FlashSuccessLocaleName` | Success locale strings interpolate the name |
56
59
  | `Munra/FlashSuccessName` | Flash success `t` calls pass the name key |
57
60
  | `Munra/FullErrorMessages` | Assert full error sets with `eq`, not `include` |
58
61
  | `Munra/LetLayout` | Blank lines and order for `let` / `let!` |
62
+ | `Munra/LiteralExpectation` | Expectations use literals, not formatters or `t` |
63
+ | `Munra/ModelSpecStructure` | Model specs order associations, validations, scopes |
59
64
  | `Munra/NamedSubjectLayout` | Named `subject` first; do not repeat its body |
65
+ | `Munra/NoCurrentDateInSystemSpec` | System specs use fixed dates |
60
66
  | `Munra/NoHumanAttributeName` | Prefer `I18n.t` over `human_attribute_name` |
61
67
  | `Munra/NoInlineValidation` | Prefer `validates_with` over inline `validate` |
62
68
  | `Munra/NoLeadingDot` | No leading-dot method chains |
69
+ | `Munra/NoMixedExampleSiblings` | Do not mix bare `it` with sibling `context` |
63
70
  | `Munra/NoSharedExamples` | Disallow shared examples / contexts |
64
71
  | `Munra/NoSpecMethod` | No `def` in spec files |
65
72
  | `Munra/NoTransactionExit` | No `return` / `next` in transaction blocks |
73
+ | `Munra/OneExamplePerContext` | One `it` / `specify` per `describe` / `context` |
74
+ | `Munra/PolicyBlankDeny` | Blank id guards must deny access |
66
75
  | `Munra/ServiceObject` | `*Service` objects follow the configured shape |
67
76
  | `Munra/SuccessErrorSiblings` | Restricted `when success` / `when error` siblings |
77
+ | `Munra/ValidationsBeforeCallbacks` | Validations before ActiveRecord callbacks |
68
78
 
69
79
  ## Development
70
80
 
data/config/default.yml CHANGED
@@ -5,6 +5,22 @@ Munra:
5
5
  DocumentationBaseURL: https://ramonsantos.github.io/rubocop-munra/rubocop-munra
6
6
  DocumentationExtension: .html
7
7
 
8
+ Munra/AddressFieldsOrder:
9
+ Description: Address fields in views follow the configured field order.
10
+ Enabled: true
11
+ VersionAdded: '1.0.0'
12
+ Include:
13
+ - '**/*.erb'
14
+ - '**/*.html.erb'
15
+ OrderedFields:
16
+ - address_zip_code
17
+ - address_state
18
+ - address_city
19
+ - address_district
20
+ - address_street
21
+ - address_number
22
+ - address_complement
23
+
8
24
  Munra/AddressStateSelect:
9
25
  Description: Prefer BrazilianState.options_for_select for address_state selects.
10
26
  Enabled: true
@@ -19,6 +35,7 @@ Munra/AdminPolicy:
19
35
  Description: Admin policies inherit the configured base and avoid forbidden methods.
20
36
  Enabled: true
21
37
  VersionAdded: '0.2.0'
38
+ VersionChanged: '1.0.0'
22
39
  Include:
23
40
  - 'app/policies/admin/**/*.rb'
24
41
  ExpectedSuperclass: Admin::ApplicationPolicy
@@ -27,6 +44,15 @@ Munra/AdminPolicy:
27
44
  - edit?
28
45
  AllowedResolveFiles: []
29
46
 
47
+ Munra/BrazilianStateInclusion:
48
+ Description: address_state validates inclusion in BrazilianState::CODES.
49
+ Enabled: true
50
+ VersionAdded: '1.0.0'
51
+ Include:
52
+ - 'app/models/**/*.rb'
53
+ Attribute: address_state
54
+ InclusionConstant: BrazilianState::CODES
55
+
30
56
  Munra/BuiltinValidationOptions:
31
57
  Description: Prefer validates_with for custom validations instead of shorthand keys.
32
58
  Enabled: true
@@ -47,7 +73,7 @@ Munra/BuiltinValidationOptions:
47
73
  - allow_blank
48
74
  - if
49
75
  - unless
50
- - on
76
+ - 'on'
51
77
  - strict
52
78
  - message
53
79
  - scope
@@ -64,10 +90,24 @@ Munra/CustomValidator:
64
90
  ForbiddenSuperclassPattern: EachValidator
65
91
  RequiredMethod: validate
66
92
 
93
+ Munra/DigitsOnlyAttributes:
94
+ Description: Digit attributes use normalizes_digits_only instead of manual callbacks.
95
+ Enabled: true
96
+ VersionAdded: '1.0.0'
97
+ Include:
98
+ - 'app/models/**/*.rb'
99
+ Attributes:
100
+ - cpf
101
+ - phone
102
+ - address_zip_code
103
+ NormalizerMethod: normalizes_digits_only
104
+
67
105
  Munra/EmailFormat:
68
106
  Description: Email attributes use EmailFormatValidator and skip Devise validatable.
69
107
  Enabled: true
70
108
  VersionAdded: '0.2.0'
109
+ Include:
110
+ - 'app/models/**/*.rb'
71
111
  Attribute: email
72
112
  Validator: EmailFormatValidator
73
113
  DeviseSkipModule: validatable
@@ -103,6 +143,28 @@ Munra/LetLayout:
103
143
  Include:
104
144
  - '**/spec/**/*.rb'
105
145
 
146
+ Munra/LiteralExpectation:
147
+ Description: Expectations use literals instead of formatters or I18n.t.
148
+ Enabled: true
149
+ VersionAdded: '1.0.0'
150
+ Include:
151
+ - '**/spec/**/*.rb'
152
+ ForbiddenFormatters:
153
+ - format_cpf
154
+ - format_phone
155
+ - format_cep
156
+
157
+ Munra/ModelSpecStructure:
158
+ Description: Model specs order associations, validations, and scopes sections.
159
+ Enabled: true
160
+ VersionAdded: '1.0.0'
161
+ Include:
162
+ - '**/spec/models/**/*_spec.rb'
163
+ OrderedSections:
164
+ - associations
165
+ - validations
166
+ - scopes
167
+
106
168
  Munra/NamedSubjectLayout:
107
169
  Description: Named subject must be first; do not repeat its body in expect.
108
170
  Enabled: true
@@ -116,6 +178,13 @@ Munra/NamedSubjectLayout:
116
178
  - patch
117
179
  - delete
118
180
 
181
+ Munra/NoCurrentDateInSystemSpec:
182
+ Description: System specs use fixed dates instead of Date.current or Date.today.
183
+ Enabled: true
184
+ VersionAdded: '1.0.0'
185
+ Include:
186
+ - '**/spec/system/**/*.rb'
187
+
119
188
  Munra/NoHumanAttributeName:
120
189
  Description: Prefer I18n.t over human_attribute_name.
121
190
  Enabled: true
@@ -131,6 +200,13 @@ Munra/NoLeadingDot:
131
200
  Enabled: true
132
201
  VersionAdded: '0.2.0'
133
202
 
203
+ Munra/NoMixedExampleSiblings:
204
+ Description: Do not mix bare it examples with sibling context or describe blocks.
205
+ Enabled: true
206
+ VersionAdded: '1.0.0'
207
+ Include:
208
+ - '**/spec/**/*.rb'
209
+
134
210
  Munra/NoSharedExamples:
135
211
  Description: Disallow shared examples and shared contexts.
136
212
  Enabled: true
@@ -161,6 +237,23 @@ Munra/NoTransactionExit:
161
237
  - transaction
162
238
  - with_lock
163
239
 
240
+ Munra/OneExamplePerContext:
241
+ Description: Allow only one it or specify per describe or context.
242
+ Enabled: true
243
+ VersionAdded: '1.0.0'
244
+ Include:
245
+ - '**/spec/**/*.rb'
246
+
247
+ Munra/PolicyBlankDeny:
248
+ Description: Blank account_id or employee_id guards must deny, not return true.
249
+ Enabled: true
250
+ VersionAdded: '1.0.0'
251
+ Include:
252
+ - 'app/policies/**/*.rb'
253
+ BlankAttributes:
254
+ - account_id
255
+ - employee_id
256
+
164
257
  Munra/ServiceObject:
165
258
  Description: Service objects inherit ApplicationService and keep call private.
166
259
  Enabled: true
@@ -178,3 +271,10 @@ Munra/SuccessErrorSiblings:
178
271
  AllowedContextNames:
179
272
  - when success
180
273
  - when error
274
+
275
+ Munra/ValidationsBeforeCallbacks:
276
+ Description: Declare validates and validates_with before ActiveRecord callbacks.
277
+ Enabled: true
278
+ VersionAdded: '1.0.0'
279
+ Include:
280
+ - 'app/models/**/*.rb'
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Resolves ActiveRecord `scope` names from the model file that matches a
4
+ # model spec path.
5
+ #
6
+ # Not a cop. Maps `spec/models/**/*_spec.rb` to `app/models/**/*.rb`,
7
+ # including nested namespaces. Comment-only `scope` lines are ignored.
8
+ module RuboCop::Cop::Munra::ModelScopeNames
9
+ SPEC_MODELS_MARKER = '/spec/models/'
10
+
11
+ private
12
+
13
+ def model_scope_names
14
+ path = model_path_for_spec
15
+ return [] unless path && File.exist?(path)
16
+
17
+ model_scope_names_cache[path] ||= read_model_scope_names(path)
18
+ end
19
+
20
+ def model_scope_names_cache
21
+ @model_scope_names_cache ||= {}
22
+ end
23
+
24
+ def read_model_scope_names(path)
25
+ File.read(path).gsub(/#.*$/, '').scan(/\bscope\s+:(\w+)\b/).flatten
26
+ rescue Errno::EACCES, Errno::ENOENT, ArgumentError, EncodingError
27
+ []
28
+ end
29
+
30
+ def model_path_for_spec
31
+ spec_path = File.expand_path(processed_source.file_path.to_s)
32
+ index = spec_path.index(SPEC_MODELS_MARKER)
33
+ return unless index
34
+
35
+ relative = spec_path[(index + SPEC_MODELS_MARKER.length)..].to_s
36
+ return unless relative.end_with?('_spec.rb')
37
+
38
+ model_relative = "#{relative.delete_suffix('_spec.rb')}.rb"
39
+ project_root = spec_path[0...index]
40
+ File.join(project_root, 'app/models', model_relative)
41
+ end
42
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Section and scope-example checks shared by ModelSpecStructure.
4
+ #
5
+ # Not a cop. Expects the including class to define offense messages and
6
+ # `model_scope_names` / `section_label` / `scopes_context?` / `scope_method_name`.
7
+ module RuboCop::Cop::Munra::ModelSpecSectionChecks
8
+ ASSOCIATION_CONTEXT = /\Awhen (belong_to|have_many|have_one|have_one_attached|have_and_belong_to_many)\z/
9
+
10
+ private
11
+
12
+ def check_associations_contexts(sections)
13
+ associations = sections.find { |section| section_label(section) == 'associations' }
14
+ return unless associations&.body
15
+
16
+ each_association_context(associations.body) do |child, name|
17
+ next if name&.match?(ASSOCIATION_CONTEXT)
18
+
19
+ add_offense(child, message: self.class::MSG_ASSOCIATION_CONTEXT)
20
+ end
21
+ end
22
+
23
+ def each_association_context(body)
24
+ body.each_child_node do |child|
25
+ next unless child.block_type? && child.send_node.method_name == :context
26
+
27
+ yield(child, child.send_node.arguments.first&.value&.to_s)
28
+ end
29
+ end
30
+
31
+ def check_scope_examples(sections)
32
+ declared = model_scope_names
33
+ return if declared.empty?
34
+
35
+ flag_root_scope_examples(sections, declared)
36
+ flag_unknown_scope_examples(sections, declared)
37
+ end
38
+
39
+ def flag_root_scope_examples(sections, declared)
40
+ sections.each do |section|
41
+ next unless section.send_node.method_name == :describe
42
+
43
+ name = scope_method_name(section)
44
+ next unless name && declared.include?(name)
45
+
46
+ add_offense(section, message: format(self.class::MSG_SCOPE_AT_ROOT, name: name))
47
+ end
48
+ end
49
+
50
+ def flag_unknown_scope_examples(sections, declared)
51
+ scopes_context = sections.find { |section| scopes_context?(section) }
52
+ return unless scopes_context&.body
53
+
54
+ each_scope_describe(scopes_context.body) do |child, name|
55
+ next if declared.include?(name)
56
+
57
+ add_offense(child, message: format(self.class::MSG_NOT_A_SCOPE, name: name))
58
+ end
59
+ end
60
+
61
+ def each_scope_describe(body)
62
+ body.each_child_node do |child|
63
+ next unless child.block_type? && child.send_node.method_name == :describe
64
+
65
+ name = scope_method_name(child)
66
+ next unless name
67
+
68
+ yield(child, name)
69
+ end
70
+ end
71
+ end
@@ -7,13 +7,36 @@
7
7
  #
8
8
  # `example_group?` allows a receiver so `RSpec.describe` matches.
9
9
  # `example?` and `let?` require a nil receiver (plain `it` / `let`).
10
+ # Focused and pending aliases (`fdescribe`, `xit`, …) and RSpec Rails
11
+ # `feature` are included. `scenario`, `shared_examples`, `subject`, and
12
+ # `let_it_be` are out of scope.
10
13
  module RuboCop::Cop::Munra::RSpecHelpers
11
14
  # Example-group method names treated as a group.
12
- EXAMPLE_GROUP_METHODS = %i[describe context].freeze
15
+ EXAMPLE_GROUP_METHODS = [
16
+ :describe,
17
+ :context,
18
+ :feature,
19
+ :xdescribe,
20
+ :xcontext,
21
+ :fdescribe,
22
+ :fcontext
23
+ ].freeze
24
+
13
25
  # Example method names treated as one example.
14
- EXAMPLE_METHODS = %i[it specify example].freeze
26
+ EXAMPLE_METHODS = [
27
+ :it,
28
+ :specify,
29
+ :example,
30
+ :xit,
31
+ :xspecify,
32
+ :xexample,
33
+ :fit,
34
+ :fspecify,
35
+ :fexample
36
+ ].freeze
37
+
15
38
  # Memoized helper method names.
16
- LET_METHODS = %i[let let!].freeze
39
+ LET_METHODS = [:let, :let!].freeze
17
40
 
18
41
  private
19
42
 
@@ -3,12 +3,13 @@
3
3
  # Detects `return` and `next` written directly inside a transaction block.
4
4
  #
5
5
  # Not a cop. `transaction` and `with_lock` blocks are recognized when the
6
- # receiver is omitted, a constant, or a method call. Both `block` and
7
- # `numblock` nodes are considered. `break` and `throw` are out of scope.
6
+ # receiver is omitted or is any non-literal node (local, ivar, `self`,
7
+ # constant, call, safe navigation, and so on). `block`, `numblock`, and
8
+ # `itblock` nodes are considered. `break` and `throw` are out of scope.
8
9
  module RuboCop::Cop::Munra::TransactionBlockMixin
9
10
  # Fallback method names when the including cop has no YAML override.
10
- TRANSACTION_METHODS = %i[transaction with_lock].freeze
11
- BLOCK_TYPES = %i[block numblock].freeze
11
+ TRANSACTION_METHODS = [:transaction, :with_lock].freeze
12
+ BLOCK_TYPES = [:block, :numblock, :itblock].freeze
12
13
 
13
14
  private
14
15
 
@@ -37,7 +38,7 @@ module RuboCop::Cop::Munra::TransactionBlockMixin
37
38
  def transaction_receiver?(receiver)
38
39
  return true if receiver.nil?
39
40
 
40
- receiver.const_type? || receiver.send_type?
41
+ !receiver.literal?
41
42
  end
42
43
 
43
44
  # Nearest ancestor block that is a transaction, if any.
@@ -51,7 +52,7 @@ module RuboCop::Cop::Munra::TransactionBlockMixin
51
52
  # @param node [RuboCop::AST::Node] a `return` or `next` node
52
53
  # @return [Boolean] true when that node sits in the transaction body, not inside a nested block
53
54
  def exit_in_direct_transaction_body?(node)
54
- return false unless %i[return next].include?(node.type)
55
+ return false unless [:return, :next].include?(node.type)
55
56
 
56
57
  transaction_block = direct_transaction_block_for(node)
57
58
  return false unless transaction_block
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Address fields in views must follow the configured field order.
4
+ #
5
+ # @example
6
+ # # bad
7
+ # <%= form.select :address_state, BrazilianState.options_for_select %>
8
+ # <%= render 'shared/icon_text_field', attribute: :address_zip_code %>
9
+ # <%= render 'shared/icon_text_field', attribute: :address_city %>
10
+ #
11
+ # @example
12
+ # # good
13
+ # <%= render 'shared/icon_text_field', attribute: :address_zip_code %>
14
+ # <%= form.select :address_state, BrazilianState.options_for_select %>
15
+ # <%= render 'shared/icon_text_field', attribute: :address_city %>
16
+ class RuboCop::Cop::Munra::AddressFieldsOrder < RuboCop::Cop::Base
17
+ MSG = 'Address fields must appear in order: %<fields>s.'
18
+
19
+ # ERB is not valid Ruby — Commissioner calls `on_other_file` instead of `on_new_investigation`.
20
+ def on_other_file
21
+ positions = field_positions
22
+ return if positions.size < 2
23
+
24
+ fields = ordered_fields
25
+ expected = fields.select { |field| positions.key?(field) }
26
+ actual = positions.sort_by { |_field, index| index }.map(&:first)
27
+ return if actual == expected
28
+
29
+ add_offense(source_range(0, processed_source.raw_source.length), message: offense_message)
30
+ end
31
+
32
+ private
33
+
34
+ def ordered_fields
35
+ cop_config.fetch(
36
+ 'OrderedFields',
37
+ ['address_zip_code', 'address_state', 'address_city', 'address_district', 'address_street', 'address_number', 'address_complement']
38
+ ).map(&:to_sym)
39
+ end
40
+
41
+ def field_pattern
42
+ fields = ordered_fields
43
+ @field_pattern ||= /:(#{fields.map { |field| Regexp.escape(field.to_s) }.join('|')})\b/
44
+ end
45
+
46
+ def offense_message
47
+ fields = ordered_fields.map { |field| field.to_s.delete_prefix('address_') }.join(', ')
48
+ format(MSG, fields: fields)
49
+ end
50
+
51
+ def field_positions
52
+ positions = {}
53
+
54
+ processed_source.raw_source.to_enum(:scan, field_pattern).each do
55
+ match = Regexp.last_match
56
+ field = match[1].to_sym
57
+ positions[field] ||= match.begin(0)
58
+ end
59
+
60
+ positions
61
+ end
62
+
63
+ def source_range(begin_pos, end_pos)
64
+ Parser::Source::Range.new(processed_source.buffer, begin_pos, end_pos)
65
+ end
66
+ end
@@ -51,7 +51,7 @@ class RuboCop::Cop::Munra::AddressStateSelect < RuboCop::Cop::Base
51
51
  attr = attribute_pattern
52
52
  @text_field_pattern ||= /
53
53
  (?:
54
- (?:text_field|text_field_tag|telephone_field|telephone_field_tag)\s*\(?\s*:#{attr}\b
54
+ (?<![A-Za-z0-9_])(?:text_field|text_field_tag|telephone_field|telephone_field_tag)\s*\(?\s*:#{attr}\b
55
55
  |attribute:\s*:#{attr}\b
56
56
  )
57
57
  /x
@@ -62,8 +62,8 @@ class RuboCop::Cop::Munra::AddressStateSelect < RuboCop::Cop::Base
62
62
  @select_pattern ||= /
63
63
  (?:
64
64
  \.select\s*\(?\s*:#{attr}\b
65
- |select_tag\s*\(?\s*:#{attr}\b
66
- |select\s*\(?\s*:#{attr}\b
65
+ |(?<![A-Za-z0-9_])select_tag\s*\(?\s*:#{attr}\b
66
+ |(?<![A-Za-z0-9_])select\s*\(?\s*:#{attr}\b
67
67
  )
68
68
  /x
69
69
  end
@@ -3,12 +3,20 @@
3
3
  # Ensures admin policies inherit the configured base class and do not
4
4
  # redefine forbidden predicate methods or an unrestricted `resolve`.
5
5
  #
6
+ # Recognizes both `class Admin::FooPolicy` and `module Admin; class FooPolicy`.
7
+ #
6
8
  # @example
7
9
  # # bad
8
10
  # class Admin::FooPolicy
9
11
  # end
10
12
  #
11
13
  # # bad
14
+ # module Admin
15
+ # class FooPolicy
16
+ # end
17
+ # end
18
+ #
19
+ # # bad
12
20
  # class Admin::FooPolicy < Admin::ApplicationPolicy
13
21
  # def new?
14
22
  # true
@@ -25,6 +33,12 @@
25
33
  # # good
26
34
  # class Admin::FooPolicy < Admin::ApplicationPolicy
27
35
  # end
36
+ #
37
+ # # good
38
+ # module Admin
39
+ # class FooPolicy < ApplicationPolicy
40
+ # end
41
+ # end
28
42
  class RuboCop::Cop::Munra::AdminPolicy < RuboCop::Cop::Base
29
43
  MSG_SUPER = 'Admin policies must inherit from `%<superclass>s`.'
30
44
  MSG_FORBIDDEN_METHOD = 'Do not redefine `%<method>s` in admin policies.'
@@ -45,24 +59,49 @@ class RuboCop::Cop::Munra::AdminPolicy < RuboCop::Cop::Base
45
59
  end
46
60
 
47
61
  def forbidden_methods
48
- cop_config.fetch('ForbiddenMethods', %w[new? edit? secretary? teacher? same_account?]).map(&:to_sym)
62
+ cop_config.fetch('ForbiddenMethods', ['new?', 'edit?']).map(&:to_sym)
49
63
  end
50
64
 
51
65
  def admin_policy_class?(node)
52
- name = node.identifier.source
53
- return false unless name.end_with?('Policy')
54
- return false if name.end_with?('ApplicationPolicy')
66
+ short_name = class_short_name(node)
67
+ return false unless short_name.end_with?('Policy')
68
+ return false if short_name.end_with?('ApplicationPolicy')
69
+
70
+ qualified = qualified_class_name(node)
71
+ qualified == 'Admin' || qualified.start_with?('Admin::') || qualified.split('::').include?('Admin')
72
+ end
55
73
 
56
- name == 'Admin' || name.start_with?('Admin::') || name.split('::').include?('Admin')
74
+ def class_short_name(node)
75
+ node.identifier.source.split('::').last
76
+ end
77
+
78
+ def qualified_class_name(node)
79
+ (module_nesting(node) + [node.identifier.source]).join('::')
80
+ end
81
+
82
+ def module_nesting(node)
83
+ node.each_ancestor(:module).map { |mod| mod.identifier.source }.reverse
57
84
  end
58
85
 
59
86
  def check_superclass(node)
60
87
  parent = node.parent_class
61
- return if parent&.const_type? && parent.source == expected_superclass
88
+ return if parent&.const_type? && superclass_matches?(node, parent)
62
89
 
63
90
  add_offense(node.identifier, message: format(MSG_SUPER, superclass: expected_superclass))
64
91
  end
65
92
 
93
+ def superclass_matches?(class_node, parent)
94
+ expected = expected_superclass
95
+ return true if parent.source == expected
96
+ return false unless expected.include?('::')
97
+
98
+ short = expected.split('::').last
99
+ return false unless parent.source == short
100
+
101
+ expected_modules = expected.split('::')[0...-1]
102
+ module_nesting(class_node).take(expected_modules.size) == expected_modules
103
+ end
104
+
66
105
  def check_forbidden_methods(node)
67
106
  node.each_descendant(:def).each do |def_node|
68
107
  next unless forbidden_methods.include?(def_node.method_name)
@@ -81,7 +120,15 @@ class RuboCop::Cop::Munra::AdminPolicy < RuboCop::Cop::Base
81
120
  end
82
121
 
83
122
  def allowed_resolve_file?
84
- allowed = cop_config.fetch('AllowedResolveFiles', [])
85
- allowed.include?(File.basename(processed_source.file_path))
123
+ allowed = Array(cop_config.fetch('AllowedResolveFiles', []))
124
+ return false if allowed.empty?
125
+
126
+ path = relative_file_path
127
+ allowed.any? { |entry| path == entry.to_s.delete_prefix('./') }
128
+ end
129
+
130
+ def relative_file_path
131
+ absolute = File.expand_path(processed_source.file_path.to_s)
132
+ RuboCop::PathUtil.relative_path(absolute).delete_prefix('./')
86
133
  end
87
134
  end