Method: Addressable::URI.unencode_component
- Defined in:
- lib/addressable/uri.rb
.unencode_component ⇒ String, 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.
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'lib/addressable/uri.rb', line 587 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 encoding = uri.encoding # A decoded byte on its own may not be a valid character, so the # result is built from the string's bytes and given its encoding once. # A string that can't be searched as it is raises as it did, from # gsub on the string itself. source = encoding.ascii_compatible? && uri.valid_encoding? ? uri.b : uri result = source.gsub(/%[0-9a-f]{2}/i) do |sequence| c = sequence[1..3].to_i(16).chr c.force_encoding(encoding) leave_encoded.include?(c) ? sequence : c.force_encoding(source.encoding) 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 |