Skip to content

Commit

Permalink
Set Content-Type on non-file parts
Browse files Browse the repository at this point in the history
Resolves #5
  • Loading branch information
ixti committed Jan 18, 2017
1 parent 1d15f41 commit ff9bf3d
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 22 deletions.
3 changes: 3 additions & 0 deletions lib/http/form_data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ module HTTP
# socket << "\r\n"
# socket << form.to_s
module FormData
# Default MIME type
DEFAULT_MIME = "application/octet-stream"

# CRLF
CRLF = "\r\n"

Expand Down
3 changes: 0 additions & 3 deletions lib/http/form_data/file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ module FormData
#
# FormData::File.new "/home/ixti/avatar.png"
class File
# Default MIME type
DEFAULT_MIME = "application/octet-stream"

attr_reader :mime_type, :filename

# @see DEFAULT_MIME
Expand Down
31 changes: 12 additions & 19 deletions lib/http/form_data/multipart/param.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@ module FormData
class Multipart
# Utility class to represent multi-part chunks
class Param
CONTENT_DISPOSITION = ""

# @param [#to_s] name
# @param [FormData::File, #to_s] value
def initialize(name, value)
@name = name.to_s
@value = value
@header = "Content-Disposition: form-data; name=#{@name.inspect}"
mime = value.mime_type if value.respond_to?(:mime_type)
params = ["name=#{name.to_s.inspect}"]

return unless file?
if value.is_a? FormData::File
@value = value
params << "filename=#{value.filename.inspect}"
else
@value = value.to_s
end

@header = "#{@header}; filename=#{value.filename.inspect}#{CRLF}" \
"Content-Type: #{value.mime_type}"
@header = "Content-Disposition: form-data; #{params.join '; '}" \
"#{CRLF}Content-Type: #{mime || DEFAULT_MIME}"
end

# Returns body part with headers and data.
Expand Down Expand Up @@ -46,10 +48,10 @@ def to_s
def size
size = @header.bytesize + (CRLF.bytesize * 2)

if file?
if @value.is_a? FormData::File
size + @value.size
else
size + @value.to_s.bytesize
size + @value.bytesize
end
end

Expand All @@ -70,15 +72,6 @@ def self.coerce(data)

params
end

private

# Tells whenever value is a {FormData::File} or not.
#
# @return [Boolean]
def file?
@value.is_a? FormData::File
end
end
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/lib/http/form_data/multipart_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def disposition(params)
expect(form_data.to_s).to eq [
"--#{boundary_value}#{crlf}",
"#{disposition 'name' => 'foo'}#{crlf}",
"Content-Type: application/octet-stream#{crlf}",
"#{crlf}bar#{crlf}",
"--#{boundary_value}#{crlf}",
"#{disposition 'name' => 'baz', 'filename' => file.filename}#{crlf}",
Expand Down

0 comments on commit ff9bf3d

Please sign in to comment.