rubocop-rails 2.0.1 → 2.19.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (144) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE.txt +1 -1
  3. data/README.md +52 -5
  4. data/config/default.yml +726 -32
  5. data/config/obsoletion.yml +17 -0
  6. data/lib/rubocop/cop/mixin/active_record_helper.rb +106 -0
  7. data/lib/rubocop/cop/mixin/active_record_migrations_helper.rb +32 -0
  8. data/lib/rubocop/cop/mixin/class_send_node_helper.rb +20 -0
  9. data/lib/rubocop/cop/mixin/enforce_superclass.rb +40 -0
  10. data/lib/rubocop/cop/mixin/index_method.rb +165 -0
  11. data/lib/rubocop/cop/mixin/migrations_helper.rb +26 -0
  12. data/lib/rubocop/cop/rails/action_controller_flash_before_render.rb +112 -0
  13. data/lib/rubocop/cop/rails/action_controller_test_case.rb +47 -0
  14. data/lib/rubocop/cop/rails/action_filter.rb +11 -21
  15. data/lib/rubocop/cop/rails/action_order.rb +116 -0
  16. data/lib/rubocop/cop/rails/active_record_aliases.rb +23 -24
  17. data/lib/rubocop/cop/rails/active_record_callbacks_order.rb +143 -0
  18. data/lib/rubocop/cop/rails/active_record_override.rb +3 -6
  19. data/lib/rubocop/cop/rails/active_support_aliases.rb +13 -22
  20. data/lib/rubocop/cop/rails/active_support_on_load.rb +70 -0
  21. data/lib/rubocop/cop/rails/add_column_index.rb +61 -0
  22. data/lib/rubocop/cop/rails/after_commit_override.rb +81 -0
  23. data/lib/rubocop/cop/rails/application_controller.rb +36 -0
  24. data/lib/rubocop/cop/rails/application_job.rb +9 -4
  25. data/lib/rubocop/cop/rails/application_mailer.rb +39 -0
  26. data/lib/rubocop/cop/rails/application_record.rb +9 -9
  27. data/lib/rubocop/cop/rails/arel_star.rb +47 -0
  28. data/lib/rubocop/cop/rails/assert_not.rb +8 -10
  29. data/lib/rubocop/cop/rails/attribute_default_block_value.rb +90 -0
  30. data/lib/rubocop/cop/rails/belongs_to.rb +12 -24
  31. data/lib/rubocop/cop/rails/blank.rb +40 -36
  32. data/lib/rubocop/cop/rails/bulk_change_table.rb +40 -35
  33. data/lib/rubocop/cop/rails/compact_blank.rb +111 -0
  34. data/lib/rubocop/cop/rails/content_tag.rb +93 -0
  35. data/lib/rubocop/cop/rails/create_table_with_timestamps.rb +22 -15
  36. data/lib/rubocop/cop/rails/date.rb +41 -36
  37. data/lib/rubocop/cop/rails/default_scope.rb +61 -0
  38. data/lib/rubocop/cop/rails/delegate.rb +33 -29
  39. data/lib/rubocop/cop/rails/delegate_allow_blank.rb +9 -10
  40. data/lib/rubocop/cop/rails/deprecated_active_model_errors_methods.rb +168 -0
  41. data/lib/rubocop/cop/rails/dot_separated_keys.rb +71 -0
  42. data/lib/rubocop/cop/rails/duplicate_association.rb +56 -0
  43. data/lib/rubocop/cop/rails/duplicate_scope.rb +46 -0
  44. data/lib/rubocop/cop/rails/duration_arithmetic.rb +98 -0
  45. data/lib/rubocop/cop/rails/dynamic_find_by.rb +76 -31
  46. data/lib/rubocop/cop/rails/eager_evaluation_log_message.rb +82 -0
  47. data/lib/rubocop/cop/rails/enum_hash.rb +75 -0
  48. data/lib/rubocop/cop/rails/enum_uniqueness.rb +30 -12
  49. data/lib/rubocop/cop/rails/environment_comparison.rb +70 -22
  50. data/lib/rubocop/cop/rails/environment_variable_access.rb +67 -0
  51. data/lib/rubocop/cop/rails/exit.rb +7 -13
  52. data/lib/rubocop/cop/rails/expanded_date_range.rb +102 -0
  53. data/lib/rubocop/cop/rails/file_path.rb +48 -31
  54. data/lib/rubocop/cop/rails/find_by.rb +43 -24
  55. data/lib/rubocop/cop/rails/find_by_id.rb +94 -0
  56. data/lib/rubocop/cop/rails/find_each.rb +42 -18
  57. data/lib/rubocop/cop/rails/freeze_time.rb +79 -0
  58. data/lib/rubocop/cop/rails/has_and_belongs_to_many.rb +4 -3
  59. data/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb +62 -25
  60. data/lib/rubocop/cop/rails/helper_instance_variable.rb +32 -4
  61. data/lib/rubocop/cop/rails/http_positional_arguments.rb +61 -32
  62. data/lib/rubocop/cop/rails/http_status.rb +27 -23
  63. data/lib/rubocop/cop/rails/i18n_lazy_lookup.rb +96 -0
  64. data/lib/rubocop/cop/rails/i18n_locale_assignment.rb +37 -0
  65. data/lib/rubocop/cop/rails/i18n_locale_texts.rb +110 -0
  66. data/lib/rubocop/cop/rails/ignored_columns_assignment.rb +50 -0
  67. data/lib/rubocop/cop/rails/ignored_skip_action_filter_option.rb +9 -16
  68. data/lib/rubocop/cop/rails/index_by.rb +65 -0
  69. data/lib/rubocop/cop/rails/index_with.rb +68 -0
  70. data/lib/rubocop/cop/rails/inquiry.rb +39 -0
  71. data/lib/rubocop/cop/rails/inverse_of.rb +33 -27
  72. data/lib/rubocop/cop/rails/lexically_scoped_action_filter.rb +62 -32
  73. data/lib/rubocop/cop/rails/link_to_blank.rb +31 -32
  74. data/lib/rubocop/cop/rails/mailer_name.rb +90 -0
  75. data/lib/rubocop/cop/rails/match_route.rb +120 -0
  76. data/lib/rubocop/cop/rails/migration_class_name.rb +63 -0
  77. data/lib/rubocop/cop/rails/negate_include.rb +42 -0
  78. data/lib/rubocop/cop/rails/not_null_column.rb +16 -12
  79. data/lib/rubocop/cop/rails/order_by_id.rb +51 -0
  80. data/lib/rubocop/cop/rails/output.rb +29 -10
  81. data/lib/rubocop/cop/rails/output_safety.rb +9 -4
  82. data/lib/rubocop/cop/rails/pick.rb +64 -0
  83. data/lib/rubocop/cop/rails/pluck.rb +96 -0
  84. data/lib/rubocop/cop/rails/pluck_id.rb +59 -0
  85. data/lib/rubocop/cop/rails/pluck_in_where.rb +71 -0
  86. data/lib/rubocop/cop/rails/pluralization_grammar.rb +14 -19
  87. data/lib/rubocop/cop/rails/presence.rb +54 -26
  88. data/lib/rubocop/cop/rails/present.rb +40 -37
  89. data/lib/rubocop/cop/rails/rake_environment.rb +112 -0
  90. data/lib/rubocop/cop/rails/read_write_attribute.rb +56 -18
  91. data/lib/rubocop/cop/rails/redundant_allow_nil.rb +33 -45
  92. data/lib/rubocop/cop/rails/redundant_foreign_key.rb +77 -0
  93. data/lib/rubocop/cop/rails/redundant_presence_validation_on_belongs_to.rb +257 -0
  94. data/lib/rubocop/cop/rails/redundant_receiver_in_with_options.rb +34 -32
  95. data/lib/rubocop/cop/rails/redundant_travel_back.rb +57 -0
  96. data/lib/rubocop/cop/rails/reflection_class_name.rb +56 -7
  97. data/lib/rubocop/cop/rails/refute_methods.rb +56 -35
  98. data/lib/rubocop/cop/rails/relative_date_constant.rb +52 -33
  99. data/lib/rubocop/cop/rails/render_inline.rb +41 -0
  100. data/lib/rubocop/cop/rails/render_plain_text.rb +71 -0
  101. data/lib/rubocop/cop/rails/request_referer.rb +10 -11
  102. data/lib/rubocop/cop/rails/require_dependency.rb +38 -0
  103. data/lib/rubocop/cop/rails/response_parsed_body.rb +57 -0
  104. data/lib/rubocop/cop/rails/reversible_migration.rb +122 -82
  105. data/lib/rubocop/cop/rails/reversible_migration_method_definition.rb +66 -0
  106. data/lib/rubocop/cop/rails/root_join_chain.rb +72 -0
  107. data/lib/rubocop/cop/rails/root_pathname_methods.rb +238 -0
  108. data/lib/rubocop/cop/rails/root_public_path.rb +59 -0
  109. data/lib/rubocop/cop/rails/safe_navigation.rb +55 -43
  110. data/lib/rubocop/cop/rails/safe_navigation_with_blank.rb +50 -0
  111. data/lib/rubocop/cop/rails/save_bang.rb +89 -63
  112. data/lib/rubocop/cop/rails/schema_comment.rb +104 -0
  113. data/lib/rubocop/cop/rails/scope_args.rb +8 -3
  114. data/lib/rubocop/cop/rails/short_i18n.rb +71 -0
  115. data/lib/rubocop/cop/rails/skips_model_validations.rb +53 -16
  116. data/lib/rubocop/cop/rails/squished_sql_heredocs.rb +87 -0
  117. data/lib/rubocop/cop/rails/strip_heredoc.rb +56 -0
  118. data/lib/rubocop/cop/rails/table_name_assignment.rb +44 -0
  119. data/lib/rubocop/cop/rails/three_state_boolean_column.rb +73 -0
  120. data/lib/rubocop/cop/rails/time_zone.rb +83 -67
  121. data/lib/rubocop/cop/rails/time_zone_assignment.rb +37 -0
  122. data/lib/rubocop/cop/rails/to_formatted_s.rb +46 -0
  123. data/lib/rubocop/cop/rails/to_s_with_argument.rb +78 -0
  124. data/lib/rubocop/cop/rails/top_level_hash_with_indifferent_access.rb +49 -0
  125. data/lib/rubocop/cop/rails/transaction_exit_statement.rb +99 -0
  126. data/lib/rubocop/cop/rails/uniq_before_pluck.rb +40 -49
  127. data/lib/rubocop/cop/rails/unique_validation_without_index.rb +172 -0
  128. data/lib/rubocop/cop/rails/unknown_env.rb +52 -21
  129. data/lib/rubocop/cop/rails/unused_ignored_columns.rb +76 -0
  130. data/lib/rubocop/cop/rails/validation.rb +54 -23
  131. data/lib/rubocop/cop/rails/where_equals.rb +102 -0
  132. data/lib/rubocop/cop/rails/where_exists.rb +138 -0
  133. data/lib/rubocop/cop/rails/where_missing.rb +118 -0
  134. data/lib/rubocop/cop/rails/where_not.rb +101 -0
  135. data/lib/rubocop/cop/rails/where_not_with_multiple_conditions.rb +55 -0
  136. data/lib/rubocop/cop/rails_cops.rb +78 -8
  137. data/lib/rubocop/rails/inject.rb +1 -1
  138. data/lib/rubocop/rails/schema_loader/schema.rb +191 -0
  139. data/lib/rubocop/rails/schema_loader.rb +61 -0
  140. data/lib/rubocop/rails/version.rb +5 -1
  141. data/lib/rubocop/rails.rb +3 -1
  142. data/lib/rubocop-rails.rb +22 -0
  143. metadata +120 -19
  144. data/bin/setup +0 -7
@@ -3,91 +3,82 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # Prefer the use of uniq (or distinct), before pluck instead of after.
6
+ # Prefer using `distinct` before `pluck` instead of `uniq` after `pluck`.
7
7
  #
8
- # The use of uniq before pluck is preferred because it executes within
8
+ # The use of distinct before pluck is preferred because it executes by
9
9
  # the database.
10
10
  #
11
11
  # This cop has two different enforcement modes. When the EnforcedStyle
12
- # is conservative (the default) then only calls to pluck on a constant
13
- # (i.e. a model class) before uniq are added as offenses.
12
+ # is `conservative` (the default), then only calls to `pluck` on a constant
13
+ # (i.e. a model class) before `uniq` are added as offenses.
14
14
  #
15
- # When the EnforcedStyle is aggressive then all calls to pluck before
16
- # uniq are added as offenses. This may lead to false positives as the cop
17
- # cannot distinguish between calls to pluck on an ActiveRecord::Relation
18
- # vs a call to pluck on an ActiveRecord::Associations::CollectionProxy.
15
+ # When the EnforcedStyle is `aggressive` then all calls to `pluck` before
16
+ # distinct are added as offenses. This may lead to false positives
17
+ # as the cop cannot distinguish between calls to `pluck` on an
18
+ # ActiveRecord::Relation vs a call to pluck on an
19
+ # ActiveRecord::Associations::CollectionProxy.
19
20
  #
20
- # Autocorrect is disabled by default for this cop since it may generate
21
- # false positives.
21
+ # @safety
22
+ # This cop is unsafe for autocorrection because the behavior may change
23
+ # depending on the database collation.
22
24
  #
23
25
  # @example EnforcedStyle: conservative (default)
24
- # # bad
25
- # Model.pluck(:id).uniq
26
+ # # bad - redundantly fetches duplicate values
27
+ # Album.pluck(:band_name).uniq
26
28
  #
27
29
  # # good
28
- # Model.uniq.pluck(:id)
30
+ # Album.distinct.pluck(:band_name)
29
31
  #
30
32
  # @example EnforcedStyle: aggressive
31
- # # bad
32
- # # this will return a Relation that pluck is called on
33
- # Model.where(cond: true).pluck(:id).uniq
33
+ # # bad - redundantly fetches duplicate values
34
+ # Album.pluck(:band_name).uniq
34
35
  #
35
- # # bad
36
- # # an association on an instance will return a CollectionProxy
37
- # instance.assoc.pluck(:id).uniq
36
+ # # bad - redundantly fetches duplicate values
37
+ # Album.where(year: 1985).pluck(:band_name).uniq
38
38
  #
39
- # # bad
40
- # Model.pluck(:id).uniq
39
+ # # bad - redundantly fetches duplicate values
40
+ # customer.favourites.pluck(:color).uniq
41
41
  #
42
42
  # # good
43
- # Model.uniq.pluck(:id)
43
+ # Album.distinct.pluck(:band_name)
44
+ # Album.distinct.where(year: 1985).pluck(:band_name)
45
+ # customer.favourites.distinct.pluck(:color)
44
46
  #
45
- class UniqBeforePluck < RuboCop::Cop::Cop
47
+ class UniqBeforePluck < Base
46
48
  include ConfigurableEnforcedStyle
47
49
  include RangeHelp
50
+ extend AutoCorrector
48
51
 
49
- MSG = 'Use `%<method>s` before `pluck`.'
52
+ MSG = 'Use `distinct` before `pluck`.'
53
+ RESTRICT_ON_SEND = %i[uniq].freeze
50
54
  NEWLINE = "\n"
51
- PATTERN = '[!^block (send (send %<type>s :pluck ...) ' \
52
- '${:uniq :distinct} ...)]'
55
+ PATTERN = '[!^block (send (send %<type>s :pluck ...) :uniq ...)]'
53
56
 
54
- def_node_matcher :conservative_node_match,
55
- format(PATTERN, type: 'const')
57
+ def_node_matcher :conservative_node_match, format(PATTERN, type: 'const')
56
58
 
57
- def_node_matcher :aggressive_node_match,
58
- format(PATTERN, type: '_')
59
+ def_node_matcher :aggressive_node_match, format(PATTERN, type: '_')
59
60
 
60
61
  def on_send(node)
61
- method = if style == :conservative
62
- conservative_node_match(node)
63
- else
64
- aggressive_node_match(node)
65
- end
62
+ uniq = if style == :conservative
63
+ conservative_node_match(node)
64
+ else
65
+ aggressive_node_match(node)
66
+ end
66
67
 
67
- return unless method
68
+ return unless uniq
68
69
 
69
- add_offense(node, location: :selector,
70
- message: format(MSG, method: method))
71
- end
72
-
73
- def autocorrect(node)
74
- lambda do |corrector|
70
+ add_offense(node.loc.selector) do |corrector|
75
71
  method = node.method_name
76
72
 
77
73
  corrector.remove(dot_method_with_whitespace(method, node))
78
- corrector.insert_before(node.receiver.loc.dot.begin, ".#{method}")
74
+ corrector.insert_before(node.receiver.loc.dot.begin, '.distinct')
79
75
  end
80
76
  end
81
77
 
82
78
  private
83
79
 
84
- def style_parameter_name
85
- 'EnforcedStyle'
86
- end
87
-
88
80
  def dot_method_with_whitespace(method, node)
89
- range_between(dot_method_begin_pos(method, node),
90
- node.loc.selector.end_pos)
81
+ range_between(dot_method_begin_pos(method, node), node.loc.selector.end_pos)
91
82
  end
92
83
 
93
84
  def dot_method_begin_pos(method, node)
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Rails
6
+ # When you define a uniqueness validation in Active Record model,
7
+ # you also should add a unique index for the column. There are two reasons.
8
+ # First, duplicated records may occur even if Active Record's validation
9
+ # is defined.
10
+ # Second, it will cause slow queries. The validation executes a `SELECT`
11
+ # statement with the target column when inserting/updating a record.
12
+ # If the column does not have an index and the table is large,
13
+ # the query will be heavy.
14
+ #
15
+ # Note that the cop does nothing if db/schema.rb does not exist.
16
+ #
17
+ # @example
18
+ # # bad - if the schema does not have a unique index
19
+ # validates :account, uniqueness: true
20
+ #
21
+ # # good - if the schema has a unique index
22
+ # validates :account, uniqueness: true
23
+ #
24
+ # # good - even if the schema does not have a unique index
25
+ # validates :account, length: { minimum: MIN_LENGTH }
26
+ #
27
+ class UniqueValidationWithoutIndex < Base
28
+ include ActiveRecordHelper
29
+
30
+ MSG = 'Uniqueness validation should have a unique index on the database column.'
31
+ RESTRICT_ON_SEND = %i[validates].freeze
32
+
33
+ def on_send(node)
34
+ return unless uniqueness_part(node)
35
+ return if condition_part?(node)
36
+ return unless schema
37
+
38
+ klass, table, names = find_schema_information(node)
39
+ return unless names
40
+ return if with_index?(klass, table, names)
41
+
42
+ add_offense(node)
43
+ end
44
+
45
+ private
46
+
47
+ def find_schema_information(node)
48
+ klass = class_node(node)
49
+ return unless klass
50
+
51
+ table = schema.table_by(name: table_name(klass))
52
+ names = column_names(node)
53
+
54
+ [klass, table, names]
55
+ end
56
+
57
+ def with_index?(klass, table, names)
58
+ # Compatibility for Rails 4.2.
59
+ add_indices = schema.add_indices_by(table_name: table_name(klass))
60
+
61
+ (table.indices + add_indices).any? do |index|
62
+ index.unique && (index.columns.to_set == names || include_column_names_in_expression_index?(index, names))
63
+ end
64
+ end
65
+
66
+ def include_column_names_in_expression_index?(index, column_names)
67
+ return false unless (expression_index = index.expression)
68
+
69
+ column_names.all? do |column_name|
70
+ expression_index.include?(column_name)
71
+ end
72
+ end
73
+
74
+ def column_names(node)
75
+ arg = node.first_argument
76
+ return unless arg.str_type? || arg.sym_type?
77
+
78
+ ret = [arg.value]
79
+ names_from_scope = column_names_from_scope(node)
80
+ ret.concat(names_from_scope) if names_from_scope
81
+
82
+ ret = ret.flat_map do |name|
83
+ klass = class_node(node)
84
+ resolve_relation_into_column(
85
+ name: name.to_s,
86
+ class_node: klass,
87
+ table: schema.table_by(name: table_name(klass))
88
+ )
89
+ end
90
+ ret.include?(nil) ? nil : ret.to_set
91
+ end
92
+
93
+ def column_names_from_scope(node)
94
+ uniq = uniqueness_part(node)
95
+ return unless uniq.hash_type?
96
+
97
+ scope = find_scope(uniq)
98
+ return unless scope
99
+
100
+ scope = unfreeze_scope(scope)
101
+
102
+ case scope.type
103
+ when :sym, :str
104
+ [scope.value]
105
+ when :array
106
+ array_node_to_array(scope)
107
+ end
108
+ end
109
+
110
+ def find_scope(pairs)
111
+ pairs.each_pair.find do |pair|
112
+ key = pair.key
113
+ next unless key.sym_type? && key.value == :scope
114
+
115
+ break pair.value
116
+ end
117
+ end
118
+
119
+ def unfreeze_scope(scope)
120
+ scope.send_type? && scope.method?(:freeze) ? scope.children.first : scope
121
+ end
122
+
123
+ def class_node(node)
124
+ node.each_ancestor.find(&:class_type?)
125
+ end
126
+
127
+ def uniqueness_part(node)
128
+ pairs = node.arguments.last
129
+ return unless pairs.hash_type?
130
+
131
+ pairs.each_pair.find do |pair|
132
+ next unless pair.key.sym_type? && pair.key.value == :uniqueness
133
+
134
+ break pair.value
135
+ end
136
+ end
137
+
138
+ def condition_part?(node)
139
+ pairs = node.arguments.last
140
+ return unless pairs.hash_type?
141
+
142
+ return true if condition_hash_part?(pairs, keys: %i[if unless])
143
+
144
+ uniqueness_node = uniqueness_part(node)
145
+ return unless uniqueness_node&.hash_type?
146
+
147
+ condition_hash_part?(uniqueness_node, keys: %i[if unless conditions])
148
+ end
149
+
150
+ def condition_hash_part?(pairs, keys:)
151
+ pairs.each_pair.any? do |pair|
152
+ key = pair.key
153
+ next unless key.sym_type?
154
+
155
+ keys.include?(key.value)
156
+ end
157
+ end
158
+
159
+ def array_node_to_array(node)
160
+ node.values.map do |elm|
161
+ case elm.type
162
+ when :str, :sym
163
+ elm.value
164
+ else
165
+ return nil
166
+ end
167
+ end
168
+ end
169
+ end
170
+ end
171
+ end
172
+ end
@@ -3,55 +3,86 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop checks that environments called with `Rails.env` predicates
6
+ # Checks that environments called with `Rails.env` predicates
7
7
  # exist.
8
+ # By default the cop allows three environments which Rails ships with:
9
+ # `development`, `test`, and `production`.
10
+ # More can be added to the `Environments` config parameter.
8
11
  #
9
12
  # @example
10
13
  # # bad
11
14
  # Rails.env.proudction?
15
+ # Rails.env == 'proudction'
12
16
  #
13
17
  # # good
14
18
  # Rails.env.production?
15
- class UnknownEnv < Cop
16
- include NameSimilarity
17
-
19
+ # Rails.env == 'production'
20
+ class UnknownEnv < Base
18
21
  MSG = 'Unknown environment `%<name>s`.'
19
- MSG_SIMILAR = 'Unknown environment `%<name>s`. ' \
20
- 'Did you mean `%<similar>s`?'
22
+ MSG_SIMILAR = 'Unknown environment `%<name>s`. Did you mean `%<similar>s`?'
21
23
 
22
- def_node_matcher :unknown_environment?, <<-PATTERN
24
+ def_node_matcher :rails_env?, <<~PATTERN
23
25
  (send
24
- (send
25
- {(const nil? :Rails) (const (cbase) :Rails)}
26
- :env)
27
- $#unknown_env_name?)
26
+ {(const nil? :Rails) (const (cbase) :Rails)}
27
+ :env)
28
+ PATTERN
29
+
30
+ def_node_matcher :unknown_environment_predicate?, <<~PATTERN
31
+ (send #rails_env? $#unknown_env_predicate?)
32
+ PATTERN
33
+
34
+ def_node_matcher :unknown_environment_equal?, <<~PATTERN
35
+ {
36
+ (send #rails_env? {:== :===} $(str #unknown_env_name?))
37
+ (send $(str #unknown_env_name?) {:== :===} #rails_env?)
38
+ }
28
39
  PATTERN
29
40
 
30
41
  def on_send(node)
31
- unknown_environment?(node) do |name|
32
- add_offense(node, location: :selector, message: message(name))
42
+ unknown_environment_predicate?(node) do |name|
43
+ add_offense(node.loc.selector, message: message(name))
44
+ end
45
+
46
+ unknown_environment_equal?(node) do |str_node|
47
+ name = str_node.value
48
+ add_offense(str_node, message: message(name))
33
49
  end
34
50
  end
35
51
 
36
52
  private
37
53
 
38
54
  def collect_variable_like_names(_scope)
39
- environments.map { |env| env + '?' }
55
+ environments
40
56
  end
41
57
 
42
58
  def message(name)
43
- similar = find_similar_name(name.to_s, [])
44
- if similar
45
- format(MSG_SIMILAR, name: name, similar: similar)
46
- else
59
+ name = name.to_s.chomp('?')
60
+
61
+ # DidYouMean::SpellChecker is not available in all versions of Ruby,
62
+ # and even on versions where it *is* available (>= 2.3), it is not
63
+ # always required correctly. So we do a feature check first. See:
64
+ # https://github.com/rubocop/rubocop/issues/7979
65
+ similar_names = if defined?(DidYouMean::SpellChecker)
66
+ spell_checker = DidYouMean::SpellChecker.new(dictionary: environments)
67
+ spell_checker.correct(name)
68
+ else
69
+ []
70
+ end
71
+
72
+ if similar_names.empty?
47
73
  format(MSG, name: name)
74
+ else
75
+ format(MSG_SIMILAR, name: name, similar: similar_names.join(', '))
48
76
  end
49
77
  end
50
78
 
51
- def unknown_env_name?(name)
79
+ def unknown_env_predicate?(name)
52
80
  name = name.to_s
53
- name.end_with?('?') &&
54
- !environments.include?(name[0..-2])
81
+ name.end_with?('?') && !environments.include?(name[0..-2])
82
+ end
83
+
84
+ def unknown_env_name?(name)
85
+ !environments.include?(name)
55
86
  end
56
87
 
57
88
  def environments
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Rails
6
+ # Suggests you remove a column that does not exist in the schema from `ignored_columns`.
7
+ # `ignored_columns` is necessary to drop a column from RDBMS, but you don't need it after the migration
8
+ # to drop the column. You avoid forgetting to remove `ignored_columns` by this cop.
9
+ #
10
+ # @example
11
+ # # bad
12
+ # class User < ApplicationRecord
13
+ # self.ignored_columns = [:already_removed_column]
14
+ # end
15
+ #
16
+ # # good
17
+ # class User < ApplicationRecord
18
+ # self.ignored_columns = [:still_existing_column]
19
+ # end
20
+ #
21
+ class UnusedIgnoredColumns < Base
22
+ include ActiveRecordHelper
23
+
24
+ MSG = 'Remove `%<column_name>s` from `ignored_columns` because the column does not exist.'
25
+ RESTRICT_ON_SEND = %i[ignored_columns=].freeze
26
+
27
+ def_node_matcher :ignored_columns, <<~PATTERN
28
+ (send self :ignored_columns= $array)
29
+ PATTERN
30
+
31
+ def_node_matcher :appended_ignored_columns, <<~PATTERN
32
+ (op-asgn (send self :ignored_columns) :+ $array)
33
+ PATTERN
34
+
35
+ def_node_matcher :column_name, <<~PATTERN
36
+ ({str sym} $_)
37
+ PATTERN
38
+
39
+ def on_send(node)
40
+ return unless (columns = ignored_columns(node) || appended_ignored_columns(node))
41
+ return unless schema
42
+
43
+ table = table(node)
44
+ return unless table
45
+
46
+ columns.children.each do |column_node|
47
+ check_column_existence(column_node, table)
48
+ end
49
+ end
50
+ alias on_op_asgn on_send
51
+
52
+ private
53
+
54
+ def check_column_existence(column_node, table)
55
+ column_name = column_name(column_node)
56
+ return unless column_name
57
+ return if table.with_column?(name: column_name.to_s)
58
+
59
+ message = format(MSG, column_name: column_name)
60
+ add_offense(column_node, message: message)
61
+ end
62
+
63
+ def class_node(node)
64
+ node.each_ancestor.find(&:class_type?)
65
+ end
66
+
67
+ def table(node)
68
+ klass = class_node(node)
69
+ return unless klass
70
+
71
+ schema.table_by(name: table_name(klass))
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop checks for the use of old-style attribute validation macros.
6
+ # Checks for the use of old-style attribute validation macros.
7
7
  #
8
8
  # @example
9
9
  # # bad
@@ -32,9 +32,10 @@ module RuboCop
32
32
  # validates :foo, size: true
33
33
  # validates :foo, uniqueness: true
34
34
  #
35
- class Validation < Cop
36
- MSG = 'Prefer the new style validations `%<prefer>s` over ' \
37
- '`%<current>s`.'
35
+ class Validation < Base
36
+ extend AutoCorrector
37
+
38
+ MSG = 'Prefer the new style validations `%<prefer>s` over `%<current>s`.'
38
39
 
39
40
  TYPES = %w[
40
41
  acceptance
@@ -50,21 +51,19 @@ module RuboCop
50
51
  uniqueness
51
52
  ].freeze
52
53
 
53
- DENYLIST = TYPES.map { |p| "validates_#{p}_of".to_sym }.freeze
54
+ RESTRICT_ON_SEND = TYPES.map { |p| "validates_#{p}_of".to_sym }.freeze
54
55
  ALLOWLIST = TYPES.map { |p| "validates :column, #{p}: value" }.freeze
55
56
 
56
57
  def on_send(node)
57
- return unless !node.receiver && DENYLIST.include?(node.method_name)
58
+ return if node.receiver
58
59
 
59
- add_offense(node, location: :selector)
60
- end
60
+ range = node.loc.selector
61
61
 
62
- def autocorrect(node)
63
- last_argument = node.arguments.last
64
- return if !last_argument.literal? && !last_argument.splat_type?
62
+ add_offense(range, message: message(node)) do |corrector|
63
+ last_argument = node.arguments.last
64
+ return if !last_argument.literal? && !last_argument.splat_type? && !frozen_array_argument?(last_argument)
65
65
 
66
- lambda do |corrector|
67
- corrector.replace(node.loc.selector, 'validates')
66
+ corrector.replace(range, 'validates')
68
67
  correct_validate_type(corrector, node)
69
68
  end
70
69
  end
@@ -72,28 +71,60 @@ module RuboCop
72
71
  private
73
72
 
74
73
  def message(node)
75
- format(MSG, prefer: preferred_method(node.method_name),
76
- current: node.method_name)
74
+ method_name = node.method_name
75
+
76
+ format(MSG, prefer: preferred_method(method_name), current: method_name)
77
77
  end
78
78
 
79
79
  def preferred_method(method)
80
- ALLOWLIST[DENYLIST.index(method.to_sym)]
80
+ ALLOWLIST[RESTRICT_ON_SEND.index(method.to_sym)]
81
81
  end
82
82
 
83
83
  def correct_validate_type(corrector, node)
84
- last_argument = node.arguments.last
85
- validate_type = node.method_name.to_s.split('_')[1]
84
+ last_argument = node.last_argument
86
85
 
87
86
  if last_argument.hash_type?
88
- corrector.replace(
89
- last_argument.loc.expression,
90
- "#{validate_type}: #{braced_options(last_argument)}"
91
- )
87
+ correct_validate_type_for_hash(corrector, node, last_argument)
88
+ elsif last_argument.array_type?
89
+ loc = last_argument.loc
90
+
91
+ correct_validate_type_for_array(corrector, node, last_argument, loc)
92
+ elsif frozen_array_argument?(last_argument)
93
+ arguments = node.last_argument.receiver
94
+ loc = arguments.parent.loc
95
+
96
+ correct_validate_type_for_array(corrector, node, arguments, loc)
92
97
  else
93
98
  range = last_argument.source_range
94
99
 
95
- corrector.insert_after(range, ", #{validate_type}: true")
100
+ corrector.insert_after(range, ", #{validate_type(node)}: true")
101
+ end
102
+ end
103
+
104
+ def correct_validate_type_for_hash(corrector, node, arguments)
105
+ corrector.replace(arguments, "#{validate_type(node)}: #{braced_options(arguments)}")
106
+ end
107
+
108
+ def correct_validate_type_for_array(corrector, node, arguments, loc)
109
+ attributes = []
110
+
111
+ arguments.each_child_node do |child_node|
112
+ attributes << if arguments.percent_literal?
113
+ ":#{child_node.source}"
114
+ else
115
+ child_node.source
116
+ end
96
117
  end
118
+
119
+ corrector.replace(loc.expression, "#{attributes.join(', ')}, #{validate_type(node)}: true")
120
+ end
121
+
122
+ def validate_type(node)
123
+ node.method_name.to_s.split('_')[1]
124
+ end
125
+
126
+ def frozen_array_argument?(argument)
127
+ argument.send_type? && argument.method?(:freeze)
97
128
  end
98
129
 
99
130
  def braced_options(options)