Method: Addressable::URI.unencode_component

Defined in:
lib/addressable/uri.rb

.unencode_componentString, Addressable::URI

Unencodes any percent encoded characters within a URI component. This method may be used for unencoding either components or full URIs, however, it is recommended to use the unencode_component alias when unencoding components.

Parameters:

  • uri (String, Addressable::URI, #to_str)

    The URI or component to unencode.

  • return_type (Class)

    The type of object to return. This value may only be set to String or Addressable::URI. All other values are invalid. Defaults to String.

  • leave_encoded (String)

    A string of characters to leave encoded. If a percent encoded character in this list is encountered then it will remain percent encoded.

Returns:

  • (String, Addressable::URI)

    The unencoded component or URI. The return type is determined by the return_type parameter.



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/addressable/uri.rb', line 502

def self.unencode(uri, return_type=String, leave_encoded='')
  return nil if uri.nil?

  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?(return_type)
    raise TypeError,
      "Expected Class (String or Addressable::URI), " +
      "got #{return_type.inspect}"
  end

  result = uri.gsub(/%[0-9a-f]{2}/i) do |sequence|
    c = sequence[1..3].to_i(16).chr
    c.force_encoding(sequence.encoding)
    leave_encoded.include?(c) ? sequence : c
  end

  result.force_encoding(Encoding::UTF_8)
  if return_type == String
    return result
  elsif return_type == ::Addressable::URI
    return ::Addressable::URI.parse(result)
  end
end