File: active_model_errors_direct_manipulation.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (60 lines) | stat: -rw-r--r-- 2,016 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true

module RuboCop
  module Cop
    # Cop that avoid direct manipulation of ActiveModel#errors hash,
    # in preparation to upgrade to Rails 6.1
    #
    # See https://gitlab.com/gitlab-org/gitlab/-/issues/225874
    class ActiveModelErrorsDirectManipulation < RuboCop::Cop::Base
      MSG = 'Avoid manipulating errors hash directly. For more details check https://gitlab.com/gitlab-org/gitlab/-/issues/225874'

      MANIPULATIVE_METHODS = ":<< :append :clear :collect! :compact! :concat :delete :delete_at :delete_if :drop :drop_while :fill :filter! :keep_if :flatten! :insert :map! :pop :prepend :push :reject! :replace :reverse! :rotate! :select! :shift :shuffle! :slice! :sort! :sort_by! :uniq! :unshift"

      def_node_matcher :active_model_errors_root_manipulation?, <<~PATTERN
        (send
          (send
            (send {send ivar lvar} :errors)
            :[]
            ...)
          {#{MANIPULATIVE_METHODS}}
          ...)
      PATTERN

      def_node_matcher :active_model_errors_root_assignment?, <<~PATTERN
        (send
          (send {send ivar lvar} :errors)
          :[]=
          ...)
      PATTERN

      def_node_matcher :active_model_errors_manipulation?, <<~PATTERN
        (send
          (send
            (send
              (send {send ivar lvar} :errors)
              {:messages :details})
            :[]
            ...)
          {#{MANIPULATIVE_METHODS}}
          ...)
      PATTERN

      def_node_matcher :active_model_errors_assignment?, <<~PATTERN
        (send
          (send
            (send {send ivar lvar} :errors)
            {:messages :details})
          :[]=
          ...)
      PATTERN

      def on_send(node)
        add_offense(node) if active_model_errors_root_assignment?(node)
        add_offense(node) if active_model_errors_root_manipulation?(node)
        add_offense(node) if active_model_errors_manipulation?(node)
        add_offense(node) if active_model_errors_assignment?(node)
      end
    end
  end
end