class Addressable::URI

def self.normalized_encode(uri, returning=String)

Returns:
  • (String, Addressable::URI) -

Parameters:
  • returning (Class) --
  • uri (String, Addressable::URI, #to_str) --
def self.normalized_encode(uri, returning=String)
  begin
    uri = uri.to_str
  rescue NoMethodError, TypeError
    raise TypeError, "Can't convert #{uri.class} into String."
  end if !uri.is_a? String
  if ![String, ::Addressable::URI].include?(returning)
    raise TypeError,
      "Expected Class (String or Addressable::URI), " +
      "got #{returning.inspect}"
  end
  uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
  components = {
    :scheme => self.unencode_component(uri_object.scheme),
    :user => self.unencode_component(uri_object.user),
    :password => self.unencode_component(uri_object.password),
    :host => self.unencode_component(uri_object.host),
    :port => uri_object.port,
    :path => self.unencode_component(uri_object.path),
    :query => self.unencode_component(uri_object.query),
    :fragment => self.unencode_component(uri_object.fragment)
  }
  components.each do |key, value|
    if value != nil
      begin
        components[key] =
          Addressable::IDNA.unicode_normalize_kc(value.to_str)
      rescue ArgumentError
        # Likely a malformed UTF-8 character, skip unicode normalization
        components[key] = value.to_str
      end
    end
  end
  encoded_uri = Addressable::URI.new(
    :scheme => self.encode_component(components[:scheme],
      Addressable::URI::CharacterClasses::SCHEME),
    :user => self.encode_component(components[:user],
      Addressable::URI::CharacterClasses::UNRESERVED),
    :password => self.encode_component(components[:password],
      Addressable::URI::CharacterClasses::UNRESERVED),
    :host => components[:host],
    :port => components[:port],
    :path => self.encode_component(components[:path],
      Addressable::URI::CharacterClasses::PATH),
    :query => self.encode_component(components[:query],
      Addressable::URI::CharacterClasses::QUERY),
    :fragment => self.encode_component(components[:fragment],
      Addressable::URI::CharacterClasses::FRAGMENT)
  )
  if returning == String
    return encoded_uri.to_s
  elsif returning == ::Addressable::URI
    return encoded_uri
  end
end