Welcome to mirror list, hosted at ThFree Co, Russian Federation.

json.rb « gitlab « cop « rubocop - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8c9027223aa4eb574d4fafe8ec27ab05a7891bb5 (plain)
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
# frozen_string_literal: true

module RuboCop
  module Cop
    module Gitlab
      class Json < RuboCop::Cop::Cop
        MSG_SEND = <<~EOL.freeze
          Avoid calling `JSON` directly. Instead, use the `Gitlab::Json`
          wrapper. This allows us to alter the JSON parser being used.
        EOL

        def_node_matcher :json_node?, <<~PATTERN
          (send (const nil? :JSON)...)
        PATTERN

        def on_send(node)
          add_offense(node, location: :expression, message: MSG_SEND) if json_node?(node)
        end

        def autocorrect(node)
          autocorrect_json_node(node)
        end

        def autocorrect_json_node(node)
          _, method_name, *arg_nodes = *node

          replacement = "Gitlab::Json.#{method_name}(#{arg_nodes.map(&:source).join(', ')})"

          lambda do |corrector|
            corrector.replace(node.source_range, replacement)
          end
        end
      end
    end
  end
end