Class: Appwrite::MultipartParser
- Inherits:
-
Object
- Object
- Appwrite::MultipartParser
- Defined in:
- lib/appwrite/multipart.rb
Instance Attribute Summary collapse
-
#parts ⇒ Object
readonly
Returns the value of attribute parts.
Instance Method Summary collapse
- #_extract_boundary(content_type) ⇒ Object
-
#initialize(multipart_string, content_type) ⇒ MultipartParser
constructor
A new instance of MultipartParser.
- #parse ⇒ Object
- #to_hash ⇒ Object
Constructor Details
#initialize(multipart_string, content_type) ⇒ MultipartParser
Returns a new instance of MultipartParser.
49 50 51 52 53 54 |
# File 'lib/appwrite/multipart.rb', line 49 def initialize(multipart_string, content_type) @multipart_string = multipart_string @boundary = _extract_boundary(content_type) @parts = {} parse end |
Instance Attribute Details
#parts ⇒ Object (readonly)
Returns the value of attribute parts.
47 48 49 |
# File 'lib/appwrite/multipart.rb', line 47 def parts @parts end |
Instance Method Details
#_extract_boundary(content_type) ⇒ Object
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/appwrite/multipart.rb', line 56 def _extract_boundary(content_type) match = content_type.match(/boundary="?(.+?)"?(?:\s*;|$)/) if match return match[1] end puts content_type raise "Boundary not found in Content-Type header" end |
#parse ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/appwrite/multipart.rb', line 67 def parse # Split the multipart string into individual parts parts = @multipart_string.split("--#{@boundary}") # Remove the first (empty) and last (boundary end) elements parts = parts[1...-1] parts.each do |part| # Split headers and content headers, content = part.strip.split("\r\n\r\n", 2) # Parse headers headers_hash = headers.split("\r\n").each_with_object({}) do |header, hash| key, value = header.split(": ", 2) hash[key.downcase] = value end # Extract name from Content-Disposition header content_disposition = headers_hash["content-disposition"] || "" name = content_disposition[/name="([^"]*)"/, 1] # If no name is found, use a default naming scheme name ||= "unnamed_part_#{@parts.length}" # Store the parsed data @parts[name] = { contents: content.strip, headers: headers_hash } end end |
#to_hash ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/appwrite/multipart.rb', line 99 def to_hash h = {} @parts.each do |name, part| case name when "responseBody" h[name] = Payload.from_binary(part[:contents]) when "responseHeaders" h[name] = part[:contents].split("\r\n").each_with_object({}) do |header, hash| key, value = header.split(": ", 2) hash[key] = value end when "responseStatusCode" h[name] = part[:contents].to_i when "duration" h[name] = part[:contents].to_f else begin h[name] = part[:contents].force_encoding("utf-8") rescue h[name] = part[:contents] end end end h end |