Method: Addressable::URI.encode_component
- Defined in:
- lib/addressable/uri.rb
.encode_component(component, character_class = CharacterClassesRegexps::RESERVED_AND_UNRESERVED, upcase_encoded = '') ⇒ String Also known as: escape_component
Percent encodes a URI component.
'9' to be percent encoded. If a Regexp is passed, the
value /[^b-zB-Z0-9]/ would have the same effect. A set of
useful String values may be found in the
Addressable::URI::CharacterClasses module. The default
value is the reserved plus unreserved character classes specified in
RFC 3986.
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
# File 'lib/addressable/uri.rb', line 482 def self.encode_component(component, character_class=CharacterClassesRegexps::RESERVED_AND_UNRESERVED, upcase_encoded='') return nil if component.nil? begin if component.kind_of?(Symbol) || component.kind_of?(Numeric) || component.kind_of?(TrueClass) || component.kind_of?(FalseClass) component = component.to_s else component = component.to_str end rescue TypeError, NoMethodError raise TypeError, "Can't convert #{component.class} into String." end if !component.is_a? String if ![String, Regexp].include?(character_class.class) raise TypeError, "Expected String or Regexp, got #{character_class.inspect}" end if character_class.kind_of?(String) character_class = /[^#{character_class}]/ end # We can't perform regexps on invalid UTF sequences, but # here we need to, so switch to ASCII. component = component.dup component.force_encoding(Encoding::ASCII_8BIT) # Avoiding gsub! because there are edge cases with frozen strings component = component.gsub(character_class) do |char| SEQUENCE_UPCASED_PERCENT_ENCODING_TABLE[char.ord] end if upcase_encoded.length > 0 upcase_encoded_chars = upcase_encoded.bytes.map do |byte| SEQUENCE_ENCODING_TABLE[byte] end component = component.gsub(/%(#{upcase_encoded_chars.join('|')})/, &:upcase) end return component end |