module Ultra7::MIME

Public Class Methods

decode_utf7(text, options={encoding: nil}) click to toggle source

Parse the given UTF-7 encoded-word text and return the corresponding decoded value.

If the `:encoding` name is not specified in the `options` hash, then the resulting string will use the default `Encoding.default_external` encoding.

@param [String] text UTF-7 encoded-word text @param [Hash] options @return [String] UTF-7 decoded value @raise [ArgumentError] if text other than UTF-7 is passed in,

or the named `:encoding` cannot be found
# File lib/ultra7/mime.rb, line 23
def self.decode_utf7(text, options={encoding: nil})
  # only deal with UTF-7 encoding
  text.scan(/=\?(.*)\?[q]\?/im).each {
    e = $1
    if e and !(e=~/utf\-7/i)
      raise ArgumentError.new("Cannot decode #{e} as UTF-7!")
    end
  }

  # remove any opening charset and Q-encoding start/end markers
  # for MIME encoded words
  text = text.gsub(/\?=/m, '').gsub(/=\?[^?]*utf\-7\?[q]\?/im, '')

  enc = options[:encoding].nil? \
    ? Encoding.default_external \
    : Encoding.find(options[:encoding])
  
  return text.gsub(/\+(.*?)-/mn) {
    if $1.empty?
      "+"
    else
      base64 = $1
      pad = base64.length % 4
      if pad > 0
        base64 << ("=" * (4-pad))
      end
      base64.unpack("m").first.unpack("n*").pack("U*")
    end
  }.encode(enc)
end
included(base) click to toggle source

@private

# File lib/ultra7/mime.rb, line 7
def self.included(base)
  base.extend(ClassMethods)
end