Method: Addressable::URI.encode

Defined in:
lib/addressable/uri.rb

.encode(uri, return_type = String) ⇒ String, Addressable::URI Also known as: escape

Percent encodes any special characters in the URI.

Parameters:

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

    The URI to encode.

  • return_type (Class) (defaults to: String)

    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.

Returns:

  • (String, Addressable::URI)

    The encoded URI. The return type is determined by the return_type parameter.



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/addressable/uri.rb', line 616

def self.encode(uri, return_type=String)
  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
  uri_object = uri.kind_of?(self) ? uri : self.parse(uri)
  encoded_uri = Addressable::URI.new(
    :scheme => self.encode_component(uri_object.scheme,
      Addressable::URI::CharacterClassesRegexps::SCHEME),
    :authority => self.encode_component(uri_object.authority,
      Addressable::URI::CharacterClassesRegexps::AUTHORITY),
    :path => self.encode_component(uri_object.path,
      Addressable::URI::CharacterClassesRegexps::PATH),
    :query => self.encode_component(uri_object.query,
      Addressable::URI::CharacterClassesRegexps::QUERY),
    :fragment => self.encode_component(uri_object.fragment,
      Addressable::URI::CharacterClassesRegexps::FRAGMENT)
  )
  if return_type == String
    return encoded_uri.to_s
  elsif return_type == ::Addressable::URI
    return encoded_uri
  end
end