File: body.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 (43 lines) | stat: -rw-r--r-- 1,017 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
# frozen_string_literal: true

require "delegate"

module HTTPX::Transcoder
  module Body
    class Error < HTTPX::Error; end

    module_function

    class Encoder < SimpleDelegator
      def initialize(body)
        body = body.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && body.is_a?(Pathname)
        @body = body
        super
      end

      def bytesize
        if @body.respond_to?(:bytesize)
          @body.bytesize
        elsif @body.respond_to?(:to_ary)
          @body.sum(&:bytesize)
        elsif @body.respond_to?(:size)
          @body.size || Float::INFINITY
        elsif @body.respond_to?(:length)
          @body.length || Float::INFINITY
        elsif @body.respond_to?(:each)
          Float::INFINITY
        else
          raise Error, "cannot determine size of body: #{@body.inspect}"
        end
      end

      def content_type
        "application/octet-stream"
      end
    end

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