Class: Parts::FilePart

Inherits:
Object
  • Object
show all
Includes:
Part
Defined in:
lib/parts.rb

Overview

Represents a part to be filled from file IO.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Part

file?, new, #to_io

Constructor Details

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

Returns a new instance of FilePart.



56
57
58
59
60
61
62
63
# File 'lib/parts.rb', line 56

def initialize(boundary, name, io, headers = {})
  file_length = io.respond_to?(:length) ?  io.length : File.size(io.local_path)
  @head = build_head(boundary, name, io.original_filename, io.content_type, file_length,
                     io.respond_to?(:opts) ? io.opts.merge(headers) : headers)
  @foot = "\r\n"
  @length = @head.bytesize + 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.



55
56
57
# File 'lib/parts.rb', line 55

def length
  @length
end

Instance Method Details

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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/parts.rb', line 65

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

  part = ''
  part << "--#{boundary}\r\n"
  part << "Content-Disposition: #{content_disposition}; name=\"#{name.to_s}\"; filename=\"#{filename}\"\r\n"
  part << "Content-Length: #{content_len}\r\n"
  if content_id = opts["Content-ID"]
    part << "Content-ID: #{content_id}\r\n"
  end

  if headers["Content-Type"] != nil
    part <<  "Content-Type: " + headers["Content-Type"] + "\r\n"
  else
    part << "Content-Type: #{type}\r\n"
  end

  part << "Content-Transfer-Encoding: #{trans_encoding}\r\n"
  part << "\r\n"
end