Class: Parts::FilePart

Inherits:
Object
  • Object
show all
Includes:
Part
Defined in:
lib/tent-client/multipart-post/parts.rb

Overview

Represents a part to be filled from file IO.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Part

new, #to_io

Constructor Details

#initialize(boundary, name, io, options = {}) ⇒ FilePart

Returns a new instance of FilePart.



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/tent-client/multipart-post/parts.rb', line 53

def initialize(boundary, name, io, options = {})
  file_length = io.respond_to?(:length) ?  io.length : File.size(io.local_path)

  options ||= {}
  options.merge!(
    :io_opts => io.respond_to?(:opts) ? io.opts : {}
  )

  @head = build_head(boundary, name, io.original_filename, io.content_type, file_length, options)
  @foot = "\r\n"
  @length = @head.length + file_length + @foot.length
  @io = CompositeReadIO.new(StringIO.new(@head), io, StringIO.new(@foot))
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



52
53
54
# File 'lib/tent-client/multipart-post/parts.rb', line 52

def length
  @length
end

Instance Method Details

#build_head(boundary, name, filename, type, content_len, options = {}) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/tent-client/multipart-post/parts.rb', line 67

def build_head(boundary, name, filename, type, content_len, options = {})
  io_opts = options[:io_opts]
  trans_encoding = io_opts["Content-Transfer-Encoding"] || "binary"
  content_disposition = io_opts["Content-Disposition"] || "form-data"

  options[:headers] ||= {}

  part = []
  part << "--#{boundary}"
  part << %(Content-Disposition: #{content_disposition}; name="#{name.to_s}"; filename="#{filename}")
  part << "Content-Length: #{content_len}"
  if content_id = io_opts["Content-ID"]
    part << "Content-ID: #{content_id}"
  end
  part << "Content-Type: #{options[:headers].delete('Content-Type') || type}"
  part << "Content-Transfer-Encoding: #{trans_encoding}"

  options[:headers].each do |name, value|
    part << "#{name}: #{value}"
  end

  part.join("\r\n") + "\r\n\r\n"
end