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.

Parameters:

  • boundary (String)
  • name (#to_s)
  • io (IO)
  • headers (Hash) (defaults to: {})

72
73
74
75
76
77
78
79
# File 'lib/parts.rb', line 72

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


66
67
68
# File 'lib/parts.rb', line 66

def length
  @length
end

Instance Method Details

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

Parameters:

  • boundary (String)
  • name (#to_s)
  • filename (String)
  • type (String)
  • content_len (Integer)
  • opts (Hash) (defaults to: {})

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/parts.rb', line 87

def build_head(boundary, name, filename, type, content_len, opts = {})
  opts = opts.clone

  trans_encoding = opts.delete("Content-Transfer-Encoding") || "binary"
  content_disposition = opts.delete("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.delete("Content-ID")
    part << "Content-ID: #{content_id}\r\n"
  end

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

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

  opts.each do |k, v|
    part << "#{k}: #{v}\r\n"
  end

  part << "\r\n"
end