rubocop-rails 2.11.2 → 2.19.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE.txt +1 -1
  3. data/README.md +23 -2
  4. data/config/default.yml +316 -20
  5. data/config/obsoletion.yml +10 -0
  6. data/lib/rubocop/cop/mixin/active_record_helper.rb +17 -8
  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 +1 -1
  10. data/lib/rubocop/cop/mixin/index_method.rb +7 -17
  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 +2 -2
  15. data/lib/rubocop/cop/rails/action_order.rb +116 -0
  16. data/lib/rubocop/cop/rails/active_record_aliases.rb +9 -6
  17. data/lib/rubocop/cop/rails/active_record_callbacks_order.rb +8 -13
  18. data/lib/rubocop/cop/rails/active_record_override.rb +2 -5
  19. data/lib/rubocop/cop/rails/active_support_aliases.rb +1 -1
  20. data/lib/rubocop/cop/rails/active_support_on_load.rb +70 -0
  21. data/lib/rubocop/cop/rails/add_column_index.rb +3 -6
  22. data/lib/rubocop/cop/rails/after_commit_override.rb +3 -13
  23. data/lib/rubocop/cop/rails/application_controller.rb +6 -2
  24. data/lib/rubocop/cop/rails/application_job.rb +7 -3
  25. data/lib/rubocop/cop/rails/application_mailer.rb +6 -2
  26. data/lib/rubocop/cop/rails/application_record.rb +7 -2
  27. data/lib/rubocop/cop/rails/arel_star.rb +8 -2
  28. data/lib/rubocop/cop/rails/assert_not.rb +1 -1
  29. data/lib/rubocop/cop/rails/attribute_default_block_value.rb +1 -1
  30. data/lib/rubocop/cop/rails/belongs_to.rb +2 -5
  31. data/lib/rubocop/cop/rails/blank.rb +13 -13
  32. data/lib/rubocop/cop/rails/bulk_change_table.rb +28 -31
  33. data/lib/rubocop/cop/rails/compact_blank.rb +111 -0
  34. data/lib/rubocop/cop/rails/content_tag.rb +42 -33
  35. data/lib/rubocop/cop/rails/create_table_with_timestamps.rb +16 -8
  36. data/lib/rubocop/cop/rails/date.rb +12 -17
  37. data/lib/rubocop/cop/rails/default_scope.rb +1 -1
  38. data/lib/rubocop/cop/rails/delegate.rb +24 -18
  39. data/lib/rubocop/cop/rails/delegate_allow_blank.rb +2 -2
  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 +31 -15
  46. data/lib/rubocop/cop/rails/eager_evaluation_log_message.rb +6 -2
  47. data/lib/rubocop/cop/rails/enum_hash.rb +3 -4
  48. data/lib/rubocop/cop/rails/enum_uniqueness.rb +3 -6
  49. data/lib/rubocop/cop/rails/environment_comparison.rb +3 -4
  50. data/lib/rubocop/cop/rails/environment_variable_access.rb +1 -1
  51. data/lib/rubocop/cop/rails/exit.rb +1 -1
  52. data/lib/rubocop/cop/rails/expanded_date_range.rb +39 -23
  53. data/lib/rubocop/cop/rails/file_path.rb +41 -24
  54. data/lib/rubocop/cop/rails/find_by.rb +1 -1
  55. data/lib/rubocop/cop/rails/find_by_id.rb +3 -3
  56. data/lib/rubocop/cop/rails/find_each.rb +27 -4
  57. data/lib/rubocop/cop/rails/freeze_time.rb +79 -0
  58. data/lib/rubocop/cop/rails/has_and_belongs_to_many.rb +1 -1
  59. data/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb +19 -9
  60. data/lib/rubocop/cop/rails/helper_instance_variable.rb +3 -3
  61. data/lib/rubocop/cop/rails/http_positional_arguments.rb +29 -11
  62. data/lib/rubocop/cop/rails/http_status.rb +6 -11
  63. data/lib/rubocop/cop/rails/i18n_lazy_lookup.rb +96 -0
  64. data/lib/rubocop/cop/rails/i18n_locale_assignment.rb +1 -1
  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 +5 -14
  68. data/lib/rubocop/cop/rails/index_by.rb +8 -8
  69. data/lib/rubocop/cop/rails/index_with.rb +8 -8
  70. data/lib/rubocop/cop/rails/inquiry.rb +1 -1
  71. data/lib/rubocop/cop/rails/inverse_of.rb +20 -10
  72. data/lib/rubocop/cop/rails/lexically_scoped_action_filter.rb +44 -16
  73. data/lib/rubocop/cop/rails/link_to_blank.rb +4 -7
  74. data/lib/rubocop/cop/rails/mailer_name.rb +9 -5
  75. data/lib/rubocop/cop/rails/match_route.rb +1 -1
  76. data/lib/rubocop/cop/rails/migration_class_name.rb +63 -0
  77. data/lib/rubocop/cop/rails/negate_include.rb +5 -4
  78. data/lib/rubocop/cop/rails/not_null_column.rb +10 -7
  79. data/lib/rubocop/cop/rails/order_by_id.rb +2 -3
  80. data/lib/rubocop/cop/rails/output.rb +26 -10
  81. data/lib/rubocop/cop/rails/output_safety.rb +6 -2
  82. data/lib/rubocop/cop/rails/pick.rb +8 -1
  83. data/lib/rubocop/cop/rails/pluck.rb +51 -11
  84. data/lib/rubocop/cop/rails/pluck_id.rb +5 -2
  85. data/lib/rubocop/cop/rails/pluck_in_where.rb +8 -7
  86. data/lib/rubocop/cop/rails/pluralization_grammar.rb +4 -5
  87. data/lib/rubocop/cop/rails/presence.rb +22 -13
  88. data/lib/rubocop/cop/rails/present.rb +10 -13
  89. data/lib/rubocop/cop/rails/rake_environment.rb +8 -3
  90. data/lib/rubocop/cop/rails/read_write_attribute.rb +52 -15
  91. data/lib/rubocop/cop/rails/redundant_allow_nil.rb +7 -17
  92. data/lib/rubocop/cop/rails/redundant_foreign_key.rb +3 -3
  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 +31 -27
  95. data/lib/rubocop/cop/rails/redundant_travel_back.rb +57 -0
  96. data/lib/rubocop/cop/rails/reflection_class_name.rb +39 -4
  97. data/lib/rubocop/cop/rails/refute_methods.rb +1 -5
  98. data/lib/rubocop/cop/rails/relative_date_constant.rb +9 -9
  99. data/lib/rubocop/cop/rails/render_inline.rb +1 -1
  100. data/lib/rubocop/cop/rails/render_plain_text.rb +1 -1
  101. data/lib/rubocop/cop/rails/request_referer.rb +2 -3
  102. data/lib/rubocop/cop/rails/require_dependency.rb +2 -2
  103. data/lib/rubocop/cop/rails/response_parsed_body.rb +57 -0
  104. data/lib/rubocop/cop/rails/reversible_migration.rb +29 -67
  105. data/lib/rubocop/cop/rails/reversible_migration_method_definition.rb +6 -15
  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 +8 -13
  110. data/lib/rubocop/cop/rails/safe_navigation_with_blank.rb +14 -7
  111. data/lib/rubocop/cop/rails/save_bang.rb +30 -23
  112. data/lib/rubocop/cop/rails/schema_comment.rb +104 -0
  113. data/lib/rubocop/cop/rails/scope_args.rb +6 -2
  114. data/lib/rubocop/cop/rails/short_i18n.rb +3 -6
  115. data/lib/rubocop/cop/rails/skips_model_validations.rb +3 -4
  116. data/lib/rubocop/cop/rails/squished_sql_heredocs.rb +13 -8
  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 +37 -32
  121. data/lib/rubocop/cop/rails/time_zone_assignment.rb +4 -4
  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 +32 -41
  127. data/lib/rubocop/cop/rails/unique_validation_without_index.rb +16 -9
  128. data/lib/rubocop/cop/rails/unknown_env.rb +3 -5
  129. data/lib/rubocop/cop/rails/unused_ignored_columns.rb +9 -2
  130. data/lib/rubocop/cop/rails/validation.rb +5 -13
  131. data/lib/rubocop/cop/rails/where_equals.rb +6 -2
  132. data/lib/rubocop/cop/rails/where_exists.rb +11 -10
  133. data/lib/rubocop/cop/rails/where_missing.rb +118 -0
  134. data/lib/rubocop/cop/rails/where_not.rb +2 -2
  135. data/lib/rubocop/cop/rails/where_not_with_multiple_conditions.rb +55 -0
  136. data/lib/rubocop/cop/rails_cops.rb +34 -0
  137. data/lib/rubocop/rails/schema_loader/schema.rb +8 -5
  138. data/lib/rubocop/rails/version.rb +1 -1
  139. data/lib/rubocop/rails.rb +1 -1
  140. data/lib/rubocop-rails.rb +19 -0
  141. metadata +42 -8
  142. data/bin/setup +0 -7
@@ -3,21 +3,21 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop checks that `tag` is used instead of `content_tag`
7
- # because `content_tag` is legacy syntax.
6
+ # Checks legacy syntax usage of `tag`
8
7
  #
9
- # NOTE: Allow `content_tag` when the first argument is a variable because
10
- # `content_tag(name)` is simpler rather than `tag.public_send(name)`.
8
+ # NOTE: Allow `tag` when the first argument is a variable because
9
+ # `tag(name)` is simpler rather than `tag.public_send(name)`.
10
+ # And this cop will be renamed to something like `LegacyTag` in the future. (e.g. RuboCop Rails 2.0)
11
11
  #
12
12
  # @example
13
13
  # # bad
14
- # content_tag(:p, 'Hello world!')
15
- # content_tag(:br)
14
+ # tag(:p)
15
+ # tag(:br, class: 'classname')
16
16
  #
17
17
  # # good
18
- # tag.p('Hello world!')
19
- # tag.br
20
- # content_tag(name, 'Hello world!')
18
+ # tag.p
19
+ # tag.br(class: 'classname')
20
+ # tag(name, class: 'classname')
21
21
  class ContentTag < Base
22
22
  include RangeHelp
23
23
  extend AutoCorrector
@@ -25,25 +25,24 @@ module RuboCop
25
25
 
26
26
  minimum_target_rails_version 5.1
27
27
 
28
- MSG = 'Use `tag` instead of `content_tag`.'
29
- RESTRICT_ON_SEND = %i[content_tag].freeze
28
+ MSG = 'Use `tag.%<preferred_method>s` instead of `tag(%<current_argument>s)`.'
29
+ RESTRICT_ON_SEND = %i[tag].freeze
30
30
 
31
31
  def on_new_investigation
32
32
  @corrected_nodes = nil
33
33
  end
34
34
 
35
35
  def on_send(node)
36
+ return unless node.receiver.nil?
37
+ return if node.arguments.count >= 3
38
+
36
39
  first_argument = node.first_argument
37
- return if !first_argument ||
38
- allowed_argument?(first_argument) ||
39
- corrected_ancestor?(node)
40
+ return if !first_argument || allowed_argument?(first_argument) || corrected_ancestor?(node)
40
41
 
41
- add_offense(node) do |corrector|
42
- autocorrect(corrector, node)
42
+ preferred_method = node.first_argument.value.to_s.underscore
43
+ message = format(MSG, preferred_method: preferred_method, current_argument: first_argument.source)
43
44
 
44
- @corrected_nodes ||= Set.new.compare_by_identity
45
- @corrected_nodes.add(node)
46
- end
45
+ register_offense(node, message, preferred_method)
47
46
  end
48
47
 
49
48
  private
@@ -53,30 +52,40 @@ module RuboCop
53
52
  end
54
53
 
55
54
  def allowed_argument?(argument)
56
- argument.variable? || argument.send_type? || argument.const_type? || argument.splat_type?
55
+ argument.variable? ||
56
+ argument.send_type? ||
57
+ argument.const_type? ||
58
+ argument.splat_type? ||
59
+ allowed_name?(argument) ||
60
+ !argument.respond_to?(:value)
57
61
  end
58
62
 
59
- def autocorrect(corrector, node)
60
- if method_name?(node.first_argument)
61
- range = correction_range(node)
62
-
63
- rest_args = node.arguments.drop(1)
64
- replacement = "tag.#{node.first_argument.value.to_s.underscore}(#{rest_args.map(&:source).join(', ')})"
63
+ def register_offense(node, message, preferred_method)
64
+ add_offense(node, message: message) do |corrector|
65
+ autocorrect(corrector, node, preferred_method)
65
66
 
66
- corrector.replace(range, replacement)
67
- else
68
- corrector.replace(node.loc.selector, 'tag')
67
+ @corrected_nodes ||= Set.new.compare_by_identity
68
+ @corrected_nodes.add(node)
69
69
  end
70
70
  end
71
71
 
72
- def method_name?(node)
73
- return false unless node.str_type? || node.sym_type?
72
+ def autocorrect(corrector, node, preferred_method)
73
+ range = correction_range(node)
74
+
75
+ rest_args = node.arguments.drop(1)
76
+ replacement = "tag.#{preferred_method}(#{rest_args.map(&:source).join(', ')})"
77
+
78
+ corrector.replace(range, replacement)
79
+ end
80
+
81
+ def allowed_name?(argument)
82
+ return false unless argument.str_type? || argument.sym_type?
74
83
 
75
- /^[a-zA-Z_][a-zA-Z_\-0-9]*$/.match?(node.value)
84
+ !/^[a-zA-Z-][a-zA-Z\-0-9]*$/.match?(argument.value)
76
85
  end
77
86
 
78
87
  def correction_range(node)
79
- range_between(node.loc.selector.begin_pos, node.loc.expression.end_pos)
88
+ range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
80
89
  end
81
90
  end
82
91
  end
@@ -3,10 +3,12 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop checks the migration for which timestamps are not included
7
- # when creating a new table.
6
+ # Checks the migration for which timestamps are not included when creating a new table.
8
7
  # In many cases, timestamps are useful information and should be added.
9
8
  #
9
+ # NOTE: Allow `timestamps` not written when `id: false` because this emphasizes respecting
10
+ # user's editing intentions.
11
+ #
10
12
  # @example
11
13
  # # bad
12
14
  # create_table :users
@@ -40,15 +42,21 @@ module RuboCop
40
42
  #
41
43
  # t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP' }
42
44
  # end
45
+ #
46
+ # # good
47
+ # create_table :users, articles, id: false do |t|
48
+ # t.integer :user_id
49
+ # t.integer :article_id
50
+ # end
51
+ #
43
52
  class CreateTableWithTimestamps < Base
53
+ include ActiveRecordMigrationsHelper
54
+
44
55
  MSG = 'Add timestamps when creating a new table.'
45
56
  RESTRICT_ON_SEND = %i[create_table].freeze
46
57
 
47
- def_node_matcher :create_table_with_block?, <<~PATTERN
48
- (block
49
- (send nil? :create_table ...)
50
- (args (arg _var))
51
- _)
58
+ def_node_search :use_id_false_option?, <<~PATTERN
59
+ (pair (sym :id) (false))
52
60
  PATTERN
53
61
 
54
62
  def_node_matcher :create_table_with_timestamps_proc?, <<~PATTERN
@@ -66,7 +74,7 @@ module RuboCop
66
74
  PATTERN
67
75
 
68
76
  def on_send(node)
69
- return unless node.command?(:create_table)
77
+ return if !node.command?(:create_table) || use_id_false_option?(node)
70
78
 
71
79
  parent = node.parent
72
80
 
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop checks for the correct use of Date methods,
6
+ # Checks for the correct use of Date methods,
7
7
  # such as Date.today, Date.current etc.
8
8
  #
9
9
  # Using `Date.today` is dangerous, because it doesn't know anything about
@@ -22,26 +22,26 @@ module RuboCop
22
22
  # And you can set a warning for `to_time` with `AllowToTime: false`.
23
23
  # `AllowToTime` is `true` by default to prevent false positive on `DateTime` object.
24
24
  #
25
- # @example EnforcedStyle: strict
25
+ # @example EnforcedStyle: flexible (default)
26
26
  # # bad
27
- # Date.current
28
- # Date.yesterday
29
27
  # Date.today
30
28
  #
31
29
  # # good
32
30
  # Time.zone.today
33
31
  # Time.zone.today - 1.day
32
+ # Date.current
33
+ # Date.yesterday
34
+ # date.in_time_zone
34
35
  #
35
- # @example EnforcedStyle: flexible (default)
36
+ # @example EnforcedStyle: strict
36
37
  # # bad
38
+ # Date.current
39
+ # Date.yesterday
37
40
  # Date.today
38
41
  #
39
42
  # # good
40
43
  # Time.zone.today
41
44
  # Time.zone.today - 1.day
42
- # Date.current
43
- # Date.yesterday
44
- # date.in_time_zone
45
45
  #
46
46
  # @example AllowToTime: true (default)
47
47
  # # good
@@ -53,22 +53,17 @@ module RuboCop
53
53
  class Date < Base
54
54
  include ConfigurableEnforcedStyle
55
55
 
56
- MSG = 'Do not use `Date.%<method_called>s` without zone. Use ' \
57
- '`Time.zone.%<day>s` instead.'
56
+ MSG = 'Do not use `Date.%<method_called>s` without zone. Use `Time.zone.%<day>s` instead.'
58
57
 
59
- MSG_SEND = 'Do not use `%<method>s` on Date objects, because they ' \
60
- 'know nothing about the time zone in use.'
58
+ MSG_SEND = 'Do not use `%<method>s` on Date objects, because they know nothing about the time zone in use.'
61
59
 
62
60
  RESTRICT_ON_SEND = %i[to_time to_time_in_current_zone].freeze
63
61
 
64
62
  BAD_DAYS = %i[today current yesterday tomorrow].freeze
65
63
 
66
- DEPRECATED_METHODS = [
67
- { deprecated: 'to_time_in_current_zone', relevant: 'in_time_zone' }
68
- ].freeze
64
+ DEPRECATED_METHODS = [{ deprecated: 'to_time_in_current_zone', relevant: 'in_time_zone' }].freeze
69
65
 
70
- DEPRECATED_MSG = '`%<deprecated>s` is deprecated. ' \
71
- 'Use `%<relevant>s` instead.'
66
+ DEPRECATED_MSG = '`%<deprecated>s` is deprecated. Use `%<relevant>s` instead.'
72
67
 
73
68
  def on_const(node)
74
69
  mod, klass = *node.children
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop looks for uses of `default_scope`.
6
+ # Looks for uses of `default_scope`.
7
7
  #
8
8
  # @example
9
9
  # # bad
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop looks for delegations that could have been created
6
+ # Looks for delegations that could have been created
7
7
  # automatically with the `delegate` method.
8
8
  #
9
9
  # Safe navigation `&.` is ignored because Rails' `allow_nil`
@@ -24,6 +24,14 @@ module RuboCop
24
24
  # # good
25
25
  # delegate :bar, to: :foo
26
26
  #
27
+ # # bad
28
+ # def bar
29
+ # self.bar
30
+ # end
31
+ #
32
+ # # good
33
+ # delegate :bar, to: :self
34
+ #
27
35
  # # good
28
36
  # def bar
29
37
  # foo&.bar
@@ -54,12 +62,13 @@ module RuboCop
54
62
  # delegate :bar, to: :foo, prefix: true
55
63
  class Delegate < Base
56
64
  extend AutoCorrector
65
+ include VisibilityHelp
57
66
 
58
67
  MSG = 'Use `delegate` to define delegations.'
59
68
 
60
69
  def_node_matcher :delegate?, <<~PATTERN
61
70
  (def _method_name _args
62
- (send (send nil? _) _ ...))
71
+ (send {(send nil? _) (self)} _ ...))
63
72
  PATTERN
64
73
 
65
74
  def on_def(node)
@@ -73,10 +82,14 @@ module RuboCop
73
82
 
74
83
  def register_offense(node)
75
84
  add_offense(node.loc.keyword) do |corrector|
76
- delegation = ["delegate :#{node.body.method_name}", "to: :#{node.body.receiver.method_name}"]
85
+ body = node.body
86
+
87
+ receiver = body.receiver.self_type? ? 'self' : ":#{body.receiver.method_name}"
88
+
89
+ delegation = ["delegate :#{body.method_name}", "to: #{receiver}"]
77
90
  delegation << ['prefix: true'] if node.method?(prefixed_method_name(node.body))
78
91
 
79
- corrector.replace(node.source_range, delegation.join(', '))
92
+ corrector.replace(node, delegation.join(', '))
80
93
  end
81
94
  end
82
95
 
@@ -92,15 +105,12 @@ module RuboCop
92
105
  return false if arg_array.size != argument_array.size
93
106
 
94
107
  arg_array.zip(argument_array).all? do |arg, argument|
95
- arg.arg_type? &&
96
- argument.lvar_type? &&
97
- arg.children == argument.children
108
+ arg.arg_type? && argument.lvar_type? && arg.children == argument.children
98
109
  end
99
110
  end
100
111
 
101
112
  def method_name_matches?(method_name, body)
102
- method_name == body.method_name ||
103
- include_prefix_case? && method_name == prefixed_method_name(body)
113
+ method_name == body.method_name || (include_prefix_case? && method_name == prefixed_method_name(body))
104
114
  end
105
115
 
106
116
  def include_prefix_case?
@@ -108,21 +118,17 @@ module RuboCop
108
118
  end
109
119
 
110
120
  def prefixed_method_name(body)
121
+ return '' if body.receiver.self_type?
122
+
111
123
  [body.receiver.method_name, body.method_name].join('_').to_sym
112
124
  end
113
125
 
114
126
  def private_or_protected_delegation(node)
115
- line = node.first_line
116
- private_or_protected_before(line) ||
117
- private_or_protected_inline(line)
118
- end
119
-
120
- def private_or_protected_before(line)
121
- (processed_source[0..line].map(&:strip) & %w[private protected]).any?
127
+ private_or_protected_inline(node) || node_visibility(node) != :public
122
128
  end
123
129
 
124
- def private_or_protected_inline(line)
125
- processed_source[line - 1].strip.match?(/\A(private )|(protected )/)
130
+ def private_or_protected_inline(node)
131
+ processed_source[node.first_line - 1].strip.match?(/\A(private )|(protected )/)
126
132
  end
127
133
  end
128
134
  end
@@ -3,7 +3,7 @@
3
3
  module RuboCop
4
4
  module Cop
5
5
  module Rails
6
- # This cop looks for delegations that pass :allow_blank as an option
6
+ # Looks for delegations that pass :allow_blank as an option
7
7
  # instead of :allow_nil. :allow_blank is not a valid option to pass
8
8
  # to ActiveSupport#delegate.
9
9
  #
@@ -27,7 +27,7 @@ module RuboCop
27
27
  return unless (offending_node = allow_blank_option(node))
28
28
 
29
29
  add_offense(offending_node) do |corrector|
30
- corrector.replace(offending_node.key.source_range, 'allow_nil')
30
+ corrector.replace(offending_node.key, 'allow_nil')
31
31
  end
32
32
  end
33
33
  end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Rails
6
+ # Checks direct manipulation of ActiveModel#errors as hash.
7
+ # These operations are deprecated in Rails 6.1 and will not work in Rails 7.
8
+ #
9
+ # @safety
10
+ # This cop is unsafe because it can report `errors` manipulation on non-ActiveModel,
11
+ # which is obviously valid.
12
+ # The cop has no way of knowing whether a variable is an ActiveModel or not.
13
+ #
14
+ # @example
15
+ # # bad
16
+ # user.errors[:name] << 'msg'
17
+ # user.errors.messages[:name] << 'msg'
18
+ #
19
+ # # good
20
+ # user.errors.add(:name, 'msg')
21
+ #
22
+ # # bad
23
+ # user.errors[:name].clear
24
+ # user.errors.messages[:name].clear
25
+ #
26
+ # # good
27
+ # user.errors.delete(:name)
28
+ #
29
+ # # bad
30
+ # user.errors.keys.include?(:attr)
31
+ #
32
+ # # good
33
+ # user.errors.attribute_names.include?(:attr)
34
+ #
35
+ class DeprecatedActiveModelErrorsMethods < Base
36
+ include RangeHelp
37
+ extend AutoCorrector
38
+
39
+ MSG = 'Avoid manipulating ActiveModel errors as hash directly.'
40
+ AUTOCORRECTABLE_METHODS = %i[<< clear keys].freeze
41
+ INCOMPATIBLE_METHODS = %i[keys values to_h to_xml].freeze
42
+
43
+ MANIPULATIVE_METHODS = Set[
44
+ *%i[
45
+ << append clear collect! compact! concat
46
+ delete delete_at delete_if drop drop_while fill filter! keep_if
47
+ flatten! insert map! pop prepend push reject! replace reverse!
48
+ rotate! select! shift shuffle! slice! sort! sort_by! uniq! unshift
49
+ ]
50
+ ].freeze
51
+
52
+ def_node_matcher :receiver_matcher_outside_model, '{send ivar lvar}'
53
+ def_node_matcher :receiver_matcher_inside_model, '{nil? send ivar lvar}'
54
+
55
+ def_node_matcher :any_manipulation?, <<~PATTERN
56
+ {
57
+ #root_manipulation?
58
+ #root_assignment?
59
+ #errors_deprecated?
60
+ #messages_details_manipulation?
61
+ #messages_details_assignment?
62
+ }
63
+ PATTERN
64
+
65
+ def_node_matcher :root_manipulation?, <<~PATTERN
66
+ (send
67
+ (send
68
+ (send #receiver_matcher :errors) :[] ...)
69
+ MANIPULATIVE_METHODS
70
+ ...
71
+ )
72
+ PATTERN
73
+
74
+ def_node_matcher :root_assignment?, <<~PATTERN
75
+ (send
76
+ (send #receiver_matcher :errors)
77
+ :[]=
78
+ ...)
79
+ PATTERN
80
+
81
+ def_node_matcher :errors_deprecated?, <<~PATTERN
82
+ (send
83
+ (send #receiver_matcher :errors)
84
+ {:keys :values :to_h :to_xml})
85
+ PATTERN
86
+
87
+ def_node_matcher :messages_details_manipulation?, <<~PATTERN
88
+ (send
89
+ (send
90
+ (send
91
+ (send #receiver_matcher :errors)
92
+ {:messages :details})
93
+ :[]
94
+ ...)
95
+ MANIPULATIVE_METHODS
96
+ ...)
97
+ PATTERN
98
+
99
+ def_node_matcher :messages_details_assignment?, <<~PATTERN
100
+ (send
101
+ (send
102
+ (send #receiver_matcher :errors)
103
+ {:messages :details})
104
+ :[]=
105
+ ...)
106
+ PATTERN
107
+
108
+ def on_send(node)
109
+ any_manipulation?(node) do
110
+ next if target_rails_version <= 6.0 && INCOMPATIBLE_METHODS.include?(node.method_name)
111
+
112
+ add_offense(node) do |corrector|
113
+ next if skip_autocorrect?(node)
114
+
115
+ autocorrect(corrector, node)
116
+ end
117
+ end
118
+ end
119
+
120
+ private
121
+
122
+ def skip_autocorrect?(node)
123
+ return true unless AUTOCORRECTABLE_METHODS.include?(node.method_name)
124
+ return false unless (receiver = node.receiver.receiver)
125
+
126
+ receiver.send_type? && receiver.method?(:details) && node.method?(:<<)
127
+ end
128
+
129
+ def autocorrect(corrector, node)
130
+ receiver = node.receiver
131
+
132
+ range = offense_range(node, receiver)
133
+ replacement = replacement(node, receiver)
134
+
135
+ corrector.replace(range, replacement)
136
+ end
137
+
138
+ def offense_range(node, receiver)
139
+ receiver = receiver.receiver while receiver.send_type? && !receiver.method?(:errors) && receiver.receiver
140
+ range_between(receiver.source_range.end_pos, node.source_range.end_pos)
141
+ end
142
+
143
+ def replacement(node, receiver)
144
+ return '.attribute_names' if node.method?(:keys)
145
+
146
+ key = receiver.first_argument.source
147
+
148
+ case node.method_name
149
+ when :<<
150
+ value = node.first_argument.source
151
+
152
+ ".add(#{key}, #{value})"
153
+ when :clear
154
+ ".delete(#{key})"
155
+ end
156
+ end
157
+
158
+ def receiver_matcher(node)
159
+ model_file? ? receiver_matcher_inside_model(node) : receiver_matcher_outside_model(node)
160
+ end
161
+
162
+ def model_file?
163
+ processed_source.file_path.include?('/models/')
164
+ end
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Rails
6
+ # Enforces the use of dot-separated locale keys instead of specifying the `:scope` option
7
+ # with an array or a single symbol in `I18n` translation methods.
8
+ # Dot-separated notation is easier to read and trace the hierarchy.
9
+ #
10
+ # @example
11
+ # # bad
12
+ # I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
13
+ # I18n.t :title, scope: :invitation
14
+ #
15
+ # # good
16
+ # I18n.t 'activerecord.errors.messages.record_invalid'
17
+ # I18n.t :record_invalid, scope: 'activerecord.errors.messages'
18
+ #
19
+ class DotSeparatedKeys < Base
20
+ include RangeHelp
21
+ extend AutoCorrector
22
+
23
+ MSG = 'Use the dot-separated keys instead of specifying the `:scope` option.'
24
+ TRANSLATE_METHODS = %i[translate t].freeze
25
+
26
+ def_node_matcher :translate_with_scope?, <<~PATTERN
27
+ (send {nil? (const {nil? cbase} :I18n)} {:translate :t} ${sym_type? str_type?}
28
+ (hash <$(pair (sym :scope) ${array_type? sym_type?}) ...>)
29
+ )
30
+ PATTERN
31
+
32
+ def on_send(node)
33
+ return unless TRANSLATE_METHODS.include?(node.method_name)
34
+
35
+ translate_with_scope?(node) do |key_node, scope_node|
36
+ return unless should_convert_scope?(scope_node)
37
+
38
+ add_offense(scope_node) do |corrector|
39
+ # Eat the comma on the left.
40
+ range = range_with_surrounding_space(scope_node.source_range, side: :left)
41
+ range = range_with_surrounding_comma(range, :left)
42
+ corrector.remove(range)
43
+
44
+ corrector.replace(key_node, new_key(key_node, scope_node))
45
+ end
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def should_convert_scope?(scope_node)
52
+ scopes(scope_node).all?(&:basic_literal?)
53
+ end
54
+
55
+ def new_key(key_node, scope_node)
56
+ "'#{scopes(scope_node).map(&:value).join('.')}.#{key_node.value}'".squeeze('.')
57
+ end
58
+
59
+ def scopes(scope_node)
60
+ value = scope_node.value
61
+
62
+ if value.array_type?
63
+ value.values
64
+ else
65
+ [value]
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Rails
6
+ # Looks for associations that have been defined multiple times in the same file.
7
+ #
8
+ # When an association is defined multiple times on a model, Active Record overrides the
9
+ # previously defined association with the new one. Because of this, this cop's autocorrection
10
+ # simply keeps the last of any duplicates and discards the rest.
11
+ #
12
+ # @example
13
+ #
14
+ # # bad
15
+ # belongs_to :foo
16
+ # belongs_to :bar
17
+ # has_one :foo
18
+ #
19
+ # # good
20
+ # belongs_to :bar
21
+ # has_one :foo
22
+ #
23
+ class DuplicateAssociation < Base
24
+ include RangeHelp
25
+ extend AutoCorrector
26
+ include ClassSendNodeHelper
27
+
28
+ MSG = "Association `%<name>s` is defined multiple times. Don't repeat associations."
29
+
30
+ def_node_matcher :association, <<~PATTERN
31
+ (send nil? {:belongs_to :has_one :has_many :has_and_belongs_to_many} ({sym str} $_) ...)
32
+ PATTERN
33
+
34
+ def on_class(class_node)
35
+ offenses(class_node).each do |name, nodes|
36
+ nodes.each do |node|
37
+ add_offense(node, message: format(MSG, name: name)) do |corrector|
38
+ next if same_line?(nodes.last, node)
39
+
40
+ corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true))
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def offenses(class_node)
49
+ class_send_nodes(class_node).select { |node| association(node) }
50
+ .group_by { |node| association(node).to_sym }
51
+ .select { |_, nodes| nodes.length > 1 }
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end