Class: Strelka::MultipartParser

Inherits:
Object
  • Object
show all
Extended by:
Loggability, MethodUtilities
Includes:
Configurability
Defined in:
lib/strelka/multipartparser.rb

Overview

A parser for extracting uploaded files and parameters from the body of a multipart/form-data request.

Synopsis

require 'strelka/multipartmimeparser'

parser = Strelka::MultipartMimeParser.new
files, params = parser.parse( io, '---boundary' )

Authors

A class for parsing multipart mime documents from a stream.

Defined Under Namespace

Modules: FileInputField

Constant Summary collapse

CRLF_REGEXP =

Line-ending regexp. Supports UNIX line-endings for testing.

/\r?\n/
BLANK_LINE_REGEXP =

Pattern for matching a blank line

/#{CRLF_REGEXP}{2}/
HEADER_FIELD_EOL =

Line-ending for RFC5322 header fields; EOL not followed by a WSP char

/#{CRLF_REGEXP}(?!\x32|\x09)/

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from MethodUtilities

attr_predicate, attr_predicate_accessor, singleton_attr_accessor, singleton_attr_reader, singleton_attr_writer, singleton_method_alias, singleton_predicate_accessor, singleton_predicate_reader

Constructor Details

#initialize(io, boundary) ⇒ MultipartParser

Create a new Strelka::MultipartMimeParser



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/strelka/multipartparser.rb', line 73

def initialize( io, boundary )
	io        = StringIO.new( io ) unless io.respond_to?( :read )
	boundary  = '--' + boundary # unless boundary.start_with?( '--' )

	@bufsize  = self.class.bufsize || self.class.defaults.spooldir
	@spooldir = self.class.spooldir || Pathname( self.class.defaults.spooldir )
	@io       = io
	@boundary = boundary
	@fields   = {}
	@buffer   = String.new( encoding: io.internal_encoding || io.external_encoding )

	# Ensure that the buffer can contain at least a whole boundary,
	# otherwise we can't scan for it.
	@bufsize  = @boundary.bytesize * 1.5 if @bufsize < @boundary.bytesize * 1.5
	@spooldir.mkpath
end

Instance Attribute Details

#bufferObject (readonly)

The current buffer for unparsed data



99
100
101
# File 'lib/strelka/multipartparser.rb', line 99

def buffer
  @buffer
end

#fieldsObject (readonly)

Parsed form fields



96
97
98
# File 'lib/strelka/multipartparser.rb', line 96

def fields
  @fields
end

Instance Method Details

#parseObject

Parse the form data from the IO and return it as a Hash.



103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/strelka/multipartparser.rb', line 103

def parse
	self.log.debug "Starting parse: %p" % [ self ]

	# Strip off the initial boundary
	self.strip_boundary or
		raise Strelka::ParseError, "No initial boundary"

	# Now scan until we see the ending boundary (the one with the trailing '--')
	self.scan_part until @buffer.start_with?( '--' )

	self.log.debug "Finished parse. %d fields" % [ self.fields.length ]
	return self.fields
end