Class: RestClient::Payload::Multipart

Inherits:
Base
  • Object
show all
Defined in:
lib/restclient/payload.rb

Constant Summary collapse

EOL =
"\r\n"

Instance Method Summary collapse

Methods inherited from Base

#escape, #flatten_params, #initialize, #inspect, #read, #size

Constructor Details

This class inherits a constructor from RestClient::Payload::Base

Instance Method Details

#boundaryObject



158
159
160
# File 'lib/restclient/payload.rb', line 158

def boundary
	@boundary ||= rand(1_000_000).to_s
end

#build_stream(params) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/restclient/payload.rb', line 105

def build_stream(params)
	b = "--#{boundary}"

	@stream = Tempfile.new("RESTClient.Stream.#{rand(1000)}")
	@stream.write(b + EOL)

	if params.is_a? Hash
		x = flatten_params(params).to_a
	else
		x = params.to_a
	end
	
	last_index = x.length - 1
	x.each_with_index do |a, index|
		k, v = *a
		if v.respond_to?(:read) && v.respond_to?(:path)
			create_file_field(@stream, k,v)
		else
			create_regular_field(@stream, k,v)
		end
		@stream.write(EOL + b)
		@stream.write(EOL) unless last_index == index
	end
	@stream.write('--')
	@stream.write(EOL)
	@stream.seek(0)
end

#closeObject



166
167
168
# File 'lib/restclient/payload.rb', line 166

def close
	@stream.close
end

#create_file_field(s, k, v) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/restclient/payload.rb', line 140

def create_file_field(s, k, v)
	begin
		s.write("Content-Disposition: multipart/form-data; name=\"#{k}\"; filename=\"#{v.respond_to?(:original_filename) ? v.original_filename : File.basename(v.path)}\"#{EOL}")
		s.write("Content-Type: #{v.respond_to?(:content_type) ? v.content_type : mime_for(v.path)}#{EOL}")
		s.write(EOL)
		while data = v.read(8124)
			s.write(data)
		end
	ensure
		v.close
	end
end

#create_regular_field(s, k, v) ⇒ Object



133
134
135
136
137
138
# File 'lib/restclient/payload.rb', line 133

def create_regular_field(s, k, v)
	s.write("Content-Disposition: multipart/form-data; name=\"#{k}\"")
	s.write(EOL)
	s.write(EOL)
	s.write(v)
end

#headersObject



162
163
164
# File 'lib/restclient/payload.rb', line 162

def headers
	super.merge({'Content-Type' => %Q{multipart/form-data; boundary="#{boundary}"}})
end

#mime_for(path) ⇒ Object



153
154
155
156
# File 'lib/restclient/payload.rb', line 153

def mime_for(path)
	mime = MIME::Types.type_for path
	mime.empty? ? 'text/plain' : mime[0].content_type
end