File: xml.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (76 lines) | stat: -rw-r--r-- 1,832 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true

module HTTPX
  module Plugins
    #
    # This plugin supports request XML encoding/response decoding using the nokogiri gem.
    #
    # https://gitlab.com/os85/httpx/wikis/XML
    #
    module XML
      MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
      module Transcoder
        module_function

        class Encoder
          def initialize(xml)
            @raw = xml
          end

          def content_type
            charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
            "application/xml; charset=#{charset}"
          end

          def bytesize
            @raw.to_s.bytesize
          end

          def to_s
            @raw.to_s
          end
        end

        def encode(xml)
          Encoder.new(xml)
        end

        def decode(response)
          content_type = response.content_type.mime_type

          raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)

          Nokogiri::XML.method(:parse)
        end
      end

      class << self
        def load_dependencies(*)
          require "nokogiri"
        end
      end

      module ResponseMethods
        # decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
        # "application/xml" (requires the "nokogiri" gem).
        def xml
          decode(Transcoder)
        end
      end

      module RequestBodyClassMethods
        #   ..., xml: Nokogiri::XML::Node #=> xml encoder
        def initialize_body(params)
          if (xml = params.delete(:xml))
            # @type var xml: Nokogiri::XML::Node | String
            return Transcoder.encode(xml)
          end

          super
        end
      end
    end

    register_plugin(:xml, XML)
  end
end