Class: RuboCop::Cop::Rails::ResponseParsedBody

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRailsVersion
Defined in:
lib/rubocop/cop/rails/response_parsed_body.rb

Overview

Prefer ‘response.parsed_body` to custom parsing logic for `response.body`.

Examples:

# bad
JSON.parse(response.body)

# bad
Nokogiri::HTML.parse(response.body)

# bad
Nokogiri::HTML5.parse(response.body)

# good
response.parsed_body

Constant Summary collapse

RESTRICT_ON_SEND =
%i[parse].freeze

Constants included from TargetRailsVersion

TargetRailsVersion::TARGET_GEM_NAME, TargetRailsVersion::USES_REQUIRES_GEM_API

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#json_parse_response_body?(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/rails/response_parsed_body.rb', line 35

def_node_matcher :json_parse_response_body?, <<~PATTERN
  (send
    (const {nil? cbase} :JSON)
    :parse
    (send
      (send nil? :response)
      :body
    )
  )
PATTERN

#nokogiri_html_parse_response_body(node) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/rails/response_parsed_body.rb', line 47

def_node_matcher :nokogiri_html_parse_response_body, <<~PATTERN
  (send
    (const
      (const {nil? cbase} :Nokogiri)
      ${:HTML :HTML5}
    )
    :parse
    (send
      (send nil? :response)
      :body
    )
  )
PATTERN

#on_send(node) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/rubocop/cop/rails/response_parsed_body.rb', line 61

def on_send(node)
  check_json_parse_response_body(node)

  return unless target_rails_version >= 7.1

  check_nokogiri_html_parse_response_body(node)
end