Class: Addressable::URI

Inherits:
Object
  • Object
show all
Defined in:
lib/addressable/uri.rb

Overview

This is an implementation of a URI parser based on <a href=“www.ietf.org/rfc/rfc3986.txt”>RFC 3986</a>, <a href=“www.ietf.org/rfc/rfc3987.txt”>RFC 3987</a>.

Defined Under Namespace

Modules: CharacterClasses, CharacterClassesRegexps, NormalizeCharacterClasses Classes: InvalidURIError

Constant Summary collapse

SLASH =
'/'
EMPTY_STR =
''
URIREGEX =
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/
PORT_MAPPING =
{
  "http" => 80,
  "https" => 443,
  "ftp" => 21,
  "tftp" => 69,
  "sftp" => 22,
  "ssh" => 22,
  "svn+ssh" => 22,
  "telnet" => 23,
  "nntp" => 119,
  "gopher" => 70,
  "wais" => 210,
  "ldap" => 389,
  "prospero" => 1525
}.freeze
SEQUENCE_ENCODING_TABLE =

Tables used to optimize encoding operations in ‘self.encode_component` and `self.normalize_component`

(0..255).map do |byte|
  format("%02x", byte).freeze
end.freeze
SEQUENCE_UPCASED_PERCENT_ENCODING_TABLE =
(0..255).map do |byte|
  format("%%%02X", byte).freeze
end.freeze
NORMPATH =
/^(?!\/)[^\/:]*:.*$/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Addressable::URI

Creates a new uri object from component parts.

Parameters:

  • [String, (Hash)

    a customizable set of options



830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
# File 'lib/addressable/uri.rb', line 830

def initialize(options={})
  if options.has_key?(:authority)
    if (options.keys & [:userinfo, :user, :password, :host, :port]).any?
      raise ArgumentError,
        "Cannot specify both an authority and any of the components " +
        "within the authority."
    end
  end
  if options.has_key?(:userinfo)
    if (options.keys & [:user, :password]).any?
      raise ArgumentError,
        "Cannot specify both a userinfo and either the user or password."
    end
  end

  reset_ivs

  defer_validation do
    # Bunch of crazy logic required because of the composite components
    # like userinfo and authority.
    self.scheme = options[:scheme] if options[:scheme]
    self.user = options[:user] if options[:user]
    self.password = options[:password] if options[:password]
    self.userinfo = options[:userinfo] if options[:userinfo]
    self.host = options[:host] if options[:host]
    self.port = options[:port] if options[:port]
    self.authority = options[:authority] if options[:authority]
    self.path = options[:path] if options[:path]
    self.query = options[:query] if options[:query]
    self.query_values = options[:query_values] if options[:query_values]
    self.fragment = options[:fragment] if options[:fragment]
  end

  to_s # force path validation
end

Instance Attribute Details

#fragmentString

The fragment component for this URI.

Returns:

  • (String)

    The fragment component.



1810
1811
1812
# File 'lib/addressable/uri.rb', line 1810

def fragment
  @fragment
end

#hostString

The host component for this URI.

Returns:

  • (String)

    The host component.



1120
1121
1122
# File 'lib/addressable/uri.rb', line 1120

def host
  @host
end

#passwordString

The password component for this URI.

Returns:

  • (String)

    The password component.



996
997
998
# File 'lib/addressable/uri.rb', line 996

def password
  @password
end

#pathString

The path component for this URI.

Returns:

  • (String)

    The path component.



1528
1529
1530
# File 'lib/addressable/uri.rb', line 1528

def path
  @path
end

#portInteger

The port component for this URI. This is the port number actually given in the URI. This does not infer port numbers from default values.

Returns:

  • (Integer)

    The port component.



1386
1387
1388
# File 'lib/addressable/uri.rb', line 1386

def port
  @port
end

#queryString

The query component for this URI.

Returns:

  • (String)

    The query component.



1607
1608
1609
# File 'lib/addressable/uri.rb', line 1607

def query
  @query
end

#schemeString

The scheme component for this URI.

Returns:

  • (String)

    The scheme component.



890
891
892
# File 'lib/addressable/uri.rb', line 890

def scheme
  @scheme
end

#userString

The user component for this URI.

Returns:

  • (String)

    The user component.



941
942
943
# File 'lib/addressable/uri.rb', line 941

def user
  @user
end

Class Method Details

.convert_path(path) ⇒ Addressable::URI

Converts a path to a file scheme URI. If the path supplied is relative, it will be returned as a relative URI. If the path supplied is actually a non-file URI, it will parse the URI as if it had been parsed with Addressable::URI.parse. Handles all of the various Microsoft-specific formats for specifying paths.

Examples:

base = Addressable::URI.convert_path("/absolute/path/")
uri = Addressable::URI.convert_path("relative/path")
(base + uri).to_s
#=> "file:///absolute/path/relative/path"

Addressable::URI.convert_path(
  "c:\\windows\\My Documents 100%20\\foo.txt"
).to_s
#=> "file:///c:/windows/My%20Documents%20100%20/foo.txt"

Addressable::URI.convert_path("http://example.com/").to_s
#=> "http://example.com/"

Parameters:

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

    Typically a String path to a file or directory, but will return a sensible return value if an absolute URI is supplied instead.

Returns:

  • (Addressable::URI)

    The parsed file scheme URI or the original URI if some other URI scheme was provided.



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/addressable/uri.rb', line 292

def self.convert_path(path)
  # If we were given nil, return nil.
  return nil unless path
  # If a URI object is passed, just return itself.
  return path if path.kind_of?(self)
  unless path.respond_to?(:to_str)
    raise TypeError, "Can't convert #{path.class} into String."
  end
  # Otherwise, convert to a String
  path = path.to_str.strip

  path.sub!(/^file:\/?\/?/, EMPTY_STR) if path =~ /^file:\/?\/?/
  path = SLASH + path if path =~ /^([a-zA-Z])[\|:]/
  uri = self.parse(path)

  if uri.scheme == nil
    # Adjust windows-style uris
    uri.path.sub!(/^\/?([a-zA-Z])[\|:][\\\/]/) do
      "/#{$1.downcase}:/"
    end
    uri.path.tr!("\\", SLASH)
    if File.exist?(uri.path) &&
        File.stat(uri.path).directory?
      uri.path.chomp!(SLASH)
      uri.path = uri.path + '/'
    end

    # If the path is absolute, set the scheme and host.
    if uri.path.start_with?(SLASH)
      uri.scheme = "file"
      uri.host = EMPTY_STR
    end
    uri.normalize!
  end

  return uri
end

.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

.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 <code>Regexp</code> is passed, the
 value <code>/[^b-zB-Z0-9]/</code> would have the same effect. A set of
 useful <code>String</code> values may be found in the
 <code>Addressable::URI::CharacterClasses</code> module. The default
 value is the reserved plus unreserved character classes specified in
 <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.

Examples:

Addressable::URI.encode_component("simple/example", "b-zB-Z0-9")
=> "simple%2Fex%61mple"
Addressable::URI.encode_component("simple/example", /[^b-zB-Z0-9]/)
=> "simple%2Fex%61mple"
Addressable::URI.encode_component(
  "simple/example", Addressable::URI::CharacterClasses::UNRESERVED
)
=> "simple%2Fexample"

Parameters:

  • component (String, #to_str)

    The URI component to encode.

  • character_class (String, Regexp) (defaults to: CharacterClassesRegexps::RESERVED_AND_UNRESERVED)

    The characters which are not percent encoded. If a String is passed, the String must be formatted as a regular expression character class. (Do not include the surrounding square brackets.) For example, "b-zB-Z0-9" would cause everything but the letters ‘b’ through ‘z’ and the numbers ‘0’ through

  • upcase_encoded (Regexp) (defaults to: '')

    A string of characters that may already be percent encoded, and whose encodings should be upcased. This allows normalization of percent encodings for characters not included in the character_class.

Returns:

  • (String)

    The encoded component.



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/addressable/uri.rb', line 403

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

.form_encode(form_values, sort = false) ⇒ String

Encodes a set of key/value pairs according to the rules for the application/x-www-form-urlencoded MIME type.

Parameters:

  • form_values (#to_hash, #to_ary)

    The form values to encode.

  • sort (TrueClass, FalseClass) (defaults to: false)

    Sort the key/value pairs prior to encoding. Defaults to false.

Returns:

  • (String)

    The encoded value.



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/addressable/uri.rb', line 740

def self.form_encode(form_values, sort=false)
  if form_values.respond_to?(:to_hash)
    form_values = form_values.to_hash.to_a
  elsif form_values.respond_to?(:to_ary)
    form_values = form_values.to_ary
  else
    raise TypeError, "Can't convert #{form_values.class} into Array."
  end

  form_values = form_values.inject([]) do |accu, (key, value)|
    if value.kind_of?(Array)
      value.each do |v|
        accu << [key.to_s, v.to_s]
      end
    else
      accu << [key.to_s, value.to_s]
    end
    accu
  end

  if sort
    # Useful for OAuth and optimizing caching systems
    form_values = form_values.sort
  end
  escaped_form_values = form_values.map do |(key, value)|
    # Line breaks are CRLF pairs
    [
      self.encode_component(
        key.gsub(/(\r\n|\n|\r)/, "\r\n"),
        CharacterClassesRegexps::UNRESERVED
      ).gsub("%20", "+"),
      self.encode_component(
        value.gsub(/(\r\n|\n|\r)/, "\r\n"),
        CharacterClassesRegexps::UNRESERVED
      ).gsub("%20", "+")
    ]
  end
  return escaped_form_values.map do |(key, value)|
    "#{key}=#{value}"
  end.join("&")
end

.form_unencode(encoded_value) ⇒ Array

Decodes a String according to the rules for the application/x-www-form-urlencoded MIME type.

Parameters:

  • encoded_value (String, #to_str)

    The form values to decode.

Returns:

  • (Array)

    The decoded values. This is not a Hash because of the possibility for duplicate keys.



793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'lib/addressable/uri.rb', line 793

def self.form_unencode(encoded_value)
  if !encoded_value.respond_to?(:to_str)
    raise TypeError, "Can't convert #{encoded_value.class} into String."
  end
  encoded_value = encoded_value.to_str
  split_values = encoded_value.split("&").map do |pair|
    pair.split("=", 2)
  end
  return split_values.map do |(key, value)|
    [
      key ? self.unencode_component(
        key.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n") : nil,
      value ? (self.unencode_component(
        value.gsub("+", "%20")).gsub(/(\r\n|\n|\r)/, "\n")) : nil
    ]
  end
end

.heuristic_parse(uri, hints = {}) ⇒ Addressable::URI

Converts an input to a URI. The input does not have to be a valid URI — the method will use heuristics to guess what URI was intended. This is not standards-compliant, merely user-friendly.

Parameters:

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

    The URI string to parse. No parsing is performed if the object is already an Addressable::URI.

  • hints (Hash) (defaults to: {})

    A Hash of hints to the heuristic parser. Defaults to {:scheme => "http"}.

Returns:



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/addressable/uri.rb', line 191

def self.heuristic_parse(uri, hints={})
  # If we were given nil, return nil.
  return nil unless uri
  # If a URI object is passed, just return itself.
  return uri.dup if uri.kind_of?(self)

  # If a URI object of the Ruby standard library variety is passed,
  # convert it to a string, then parse the string.
  # We do the check this way because we don't want to accidentally
  # cause a missing constant exception to be thrown.
  if uri.class.name =~ /^URI\b/
    uri = uri.to_s
  end

  unless uri.respond_to?(:to_str)
    raise TypeError, "Can't convert #{uri.class} into String."
  end
  # Otherwise, convert to a String
  uri = uri.to_str.dup.strip
  hints = {
    :scheme => "http"
  }.merge(hints)
  case uri
  when /^http:\//i
    uri.sub!(/^http:\/+/i, "http://")
  when /^https:\//i
    uri.sub!(/^https:\/+/i, "https://")
  when /^feed:\/+http:\//i
    uri.sub!(/^feed:\/+http:\/+/i, "feed:http://")
  when /^feed:\//i
    uri.sub!(/^feed:\/+/i, "feed://")
  when %r[^file:/{4}]i
    uri.sub!(%r[^file:/+]i, "file:////")
  when %r[^file://localhost/]i
    uri.sub!(%r[^file://localhost/+]i, "file:///")
  when %r[^file:/+]i
    uri.sub!(%r[^file:/+]i, "file:///")
  when /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/
    uri.sub!(/^/, hints[:scheme] + "://")
  when /\A\d+\..*:\d+\z/
    uri = "#{hints[:scheme]}://#{uri}"
  end
  match = uri.match(URIREGEX)
  fragments = match.captures
  authority = fragments[3]
  if authority && authority.length > 0
    new_authority = authority.tr("\\", "/").gsub(" ", "%20")
    # NOTE: We want offset 4, not 3!
    offset = match.offset(4)
    uri = uri.dup
    uri[offset[0]...offset[1]] = new_authority
  end
  parsed = self.parse(uri)
  if parsed.scheme =~ /^[^\/?#\.]+\.[^\/?#]+$/
    parsed = self.parse(hints[:scheme] + "://" + uri)
  end
  if parsed.path.include?(".")
    if parsed.path[/\b@\b/]
      parsed.scheme = "mailto" unless parsed.scheme
    elsif new_host = parsed.path[/^([^\/]+\.[^\/]*)/, 1]
      parsed.defer_validation do
        new_path = parsed.path.sub(
          Regexp.new("^" + Regexp.escape(new_host)), EMPTY_STR)
        parsed.host = new_host
        parsed.path = new_path
        parsed.scheme = hints[:scheme] unless parsed.scheme
      end
    end
  end
  return parsed
end

.ip_based_schemesObject

Returns an array of known ip-based schemes. These schemes typically use a similar URI form: //<user>:<password>@<host>:<port>/<url-path>



1369
1370
1371
# File 'lib/addressable/uri.rb', line 1369

def self.ip_based_schemes
  return self.port_mapping.keys
end

.join(*uris) ⇒ Addressable::URI

Joins several URIs together.

Examples:

base = "http://example.com/"
uri = Addressable::URI.parse("relative/path")
Addressable::URI.join(base, uri)
#=> #<Addressable::URI:0xcab390 URI:http://example.com/relative/path>

Parameters:

Returns:



343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/addressable/uri.rb', line 343

def self.join(*uris)
  uri_objects = uris.collect do |uri|
    unless uri.respond_to?(:to_str)
      raise TypeError, "Can't convert #{uri.class} into String."
    end
    uri.kind_of?(self) ? uri : self.parse(uri.to_str)
  end
  result = uri_objects.shift.dup
  uri_objects.each do |uri|
    result.join!(uri)
  end
  return result
end

.normalize_component(component, character_class = CharacterClassesRegexps::RESERVED_AND_UNRESERVED, leave_encoded = '') ⇒ String

Normalizes the encoding of a URI component.

Examples:

Addressable::URI.normalize_component("simpl%65/%65xampl%65", "b-zB-Z")
=> "simple%2Fex%61mple"
Addressable::URI.normalize_component(
  "simpl%65/%65xampl%65", /[^b-zB-Z]/
)
=> "simple%2Fex%61mple"
Addressable::URI.normalize_component(
  "simpl%65/%65xampl%65",
  Addressable::URI::CharacterClasses::UNRESERVED
)
=> "simple%2Fexample"
Addressable::URI.normalize_component(
  "one%20two%2fthree%26four",
  "0-9a-zA-Z &/",
  "/"
)
=> "one two%2Fthree&four"

Parameters:

  • component (String, #to_str)

    The URI component to encode.

  • character_class (String, Regexp) (defaults to: CharacterClassesRegexps::RESERVED_AND_UNRESERVED)

    The characters which are not percent encoded. If a String is passed, the String must be formatted as a regular expression character class. (Do not include the surrounding square brackets.) For example, "b-zB-Z0-9" would cause everything but the letters ‘b’ through ‘z’ and the numbers ‘0’ through ‘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 <a href=“www.ietf.org/rfc/rfc3986.txt”>RFC 3986</a>.

  • leave_encoded (String) (defaults to: '')

    When character_class is a String then leave_encoded is a string of characters that should remain percent encoded while normalizing the component; if they appear percent encoded in the original component, then they will be upcased (“%2f” normalized to “%2F”) but otherwise left alone.

Returns:

  • (String)

    The normalized component.



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'lib/addressable/uri.rb', line 552

def self.normalize_component(component, character_class=
    CharacterClassesRegexps::RESERVED_AND_UNRESERVED,
    leave_encoded='')
  return nil if component.nil?

  begin
    component = component.to_str
  rescue NoMethodError, TypeError
    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)
    leave_re = if leave_encoded.length > 0
      character_class = "#{character_class}%" unless character_class.include?('%')

      bytes = leave_encoded.bytes
      leave_encoded_pattern = bytes.map { |b| SEQUENCE_ENCODING_TABLE[b] }.join('|')
      "|%(?!#{leave_encoded_pattern}|#{leave_encoded_pattern.upcase})"
    end

    character_class = if leave_re
                        /[^#{character_class}]#{leave_re}/
                      else
                        /[^#{character_class}]/
                      end
  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)
  unencoded = self.unencode_component(component, String, leave_encoded)
  begin
    encoded = self.encode_component(
      unencoded.unicode_normalize(:nfc),
      character_class,
      leave_encoded
    )
  rescue ArgumentError
    encoded = self.encode_component(unencoded)
  end
  encoded.force_encoding(Encoding::UTF_8)
  return encoded
end

.normalized_encode(uri, return_type = String) ⇒ String, Addressable::URI

Normalizes the encoding of a URI. Characters within a hostname are not percent encoded to allow for internationalized domain names.

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.



671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/addressable/uri.rb', line 671

def self.normalized_encode(uri, return_type=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?(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)
  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.nil? ? nil : uri_object.port.to_s),
    :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] = value.to_str.unicode_normalize(:nfc)
      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::CharacterClassesRegexps::SCHEME),
    :user => self.encode_component(components[:user],
      Addressable::URI::CharacterClassesRegexps::UNRESERVED),
    :password => self.encode_component(components[:password],
      Addressable::URI::CharacterClassesRegexps::UNRESERVED),
    :host => components[:host],
    :port => components[:port],
    :path => self.encode_component(components[:path],
      Addressable::URI::CharacterClassesRegexps::PATH),
    :query => self.encode_component(components[:query],
      Addressable::URI::CharacterClassesRegexps::QUERY),
    :fragment => self.encode_component(components[:fragment],
      Addressable::URI::CharacterClassesRegexps::FRAGMENT)
  )
  if return_type == String
    return encoded_uri.to_s
  elsif return_type == ::Addressable::URI
    return encoded_uri
  end
end

.parse(uri) ⇒ Addressable::URI

Returns a URI object based on the parsed string.

Parameters:

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

    The URI string to parse. No parsing is performed if the object is already an Addressable::URI.

Returns:



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/addressable/uri.rb', line 114

def self.parse(uri)
  # If we were given nil, return nil.
  return nil unless uri
  # If a URI object is passed, just return itself.
  return uri.dup if uri.kind_of?(self)

  # If a URI object of the Ruby standard library variety is passed,
  # convert it to a string, then parse the string.
  # We do the check this way because we don't want to accidentally
  # cause a missing constant exception to be thrown.
  if uri.class.name =~ /^URI\b/
    uri = uri.to_s
  end

  # Otherwise, convert to a String
  begin
    uri = uri.to_str
  rescue TypeError, NoMethodError
    raise TypeError, "Can't convert #{uri.class} into String."
  end unless uri.is_a?(String)

  # This Regexp supplied as an example in RFC 3986, and it works great.
  scan = uri.scan(URIREGEX)
  fragments = scan[0]
  scheme = fragments[1]
  authority = fragments[3]
  path = fragments[4]
  query = fragments[6]
  fragment = fragments[8]
  user = nil
  password = nil
  host = nil
  port = nil
  if authority != nil
    # The Regexp above doesn't split apart the authority.
    userinfo = authority[/^([^\[\]]*)@/, 1]
    if userinfo != nil
      user = userinfo.strip[/^([^:]*):?/, 1]
      password = userinfo.strip[/:(.*)$/, 1]
    end

    host = authority.sub(
      /^([^\[\]]*)@/, EMPTY_STR
    ).sub(
      /:([^:@\[\]]*?)$/, EMPTY_STR
    )

    port = authority[/:([^:@\[\]]*?)$/, 1]
    port = nil if port == EMPTY_STR
  end

  return new(
    :scheme => scheme,
    :user => user,
    :password => password,
    :host => host,
    :port => port,
    :path => path,
    :query => query,
    :fragment => fragment
  )
end

.port_mappingObject

Returns a hash of common IP-based schemes and their default port numbers. Adding new schemes to this hash, as necessary, will allow for better URI normalization.



1376
1377
1378
# File 'lib/addressable/uri.rb', line 1376

def self.port_mapping
  PORT_MAPPING
end

.unencode(uri, return_type = String, leave_encoded = '') ⇒ String, Addressable::URI Also known as: unescape, unencode_component, unescape_component

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) (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.

  • leave_encoded (String) (defaults to: '')

    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.



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/addressable/uri.rb', line 472

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

Instance Method Details

#==(uri) ⇒ TrueClass, FalseClass

Returns true if the URI objects are equal. This method normalizes both URIs before doing the comparison.

Parameters:

  • uri (Object)

    The URI to compare.

Returns:

  • (TrueClass, FalseClass)

    true if the URIs are equivalent, false otherwise.



2239
2240
2241
2242
# File 'lib/addressable/uri.rb', line 2239

def ==(uri)
  return false unless uri.kind_of?(URI)
  return self.normalize.to_s == uri.normalize.to_s
end

#===(uri) ⇒ TrueClass, FalseClass

Returns true if the URI objects are equal. This method normalizes both URIs before doing the comparison, and allows comparison against Strings.

Parameters:

  • uri (Object)

    The URI to compare.

Returns:

  • (TrueClass, FalseClass)

    true if the URIs are equivalent, false otherwise.



2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
# File 'lib/addressable/uri.rb', line 2217

def ===(uri)
  if uri.respond_to?(:normalize)
    uri_string = uri.normalize.to_s
  else
    begin
      uri_string = ::Addressable::URI.parse(uri).normalize.to_s
    rescue InvalidURIError, TypeError
      return false
    end
  end
  return self.normalize.to_s == uri_string
end

#absolute?TrueClass, FalseClass

Determines if the URI is absolute.

Returns:

  • (TrueClass, FalseClass)

    true if the URI is absolute. false otherwise.



1879
1880
1881
# File 'lib/addressable/uri.rb', line 1879

def absolute?
  return !relative?
end

#authorityString

The authority component for this URI. Combines the user, password, host, and port components.

Returns:

  • (String)

    The authority component.



1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/addressable/uri.rb', line 1234

def authority
  self.host && @authority ||= begin
    authority = String.new
    if self.userinfo != nil
      authority << "#{self.userinfo}@"
    end
    authority << self.host
    if self.port != nil
      authority << ":#{self.port}"
    end
    authority
  end
end

#authority=(new_authority) ⇒ Object

Sets the authority component for this URI.

Parameters:

  • new_authority (String, #to_str)

    The new authority component.



1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/addressable/uri.rb', line 1274

def authority=(new_authority)
  if new_authority
    if !new_authority.respond_to?(:to_str)
      raise TypeError, "Can't convert #{new_authority.class} into String."
    end
    new_authority = new_authority.to_str
    new_userinfo = new_authority[/^([^\[\]]*)@/, 1]
    if new_userinfo
      new_user = new_userinfo.strip[/^([^:]*):?/, 1]
      new_password = new_userinfo.strip[/:(.*)$/, 1]
    end
    new_host = new_authority.sub(
      /^([^\[\]]*)@/, EMPTY_STR
    ).sub(
      /:([^:@\[\]]*?)$/, EMPTY_STR
    )
    new_port =
      new_authority[/:([^:@\[\]]*?)$/, 1]
  end

  # Password assigned first to ensure validity in case of nil
  self.password = new_password
  self.user = new_user
  self.host = new_host
  self.port = new_port

  # Reset dependent values
  @userinfo = nil
  @normalized_userinfo = NONE
  remove_composite_values

  # Ensure we haven't created an invalid URI
  validate()
end

#basenameString

The basename, if any, of the file in the path component.

Returns:

  • (String)

    The path’s basename.



1588
1589
1590
1591
# File 'lib/addressable/uri.rb', line 1588

def basename
  # Path cannot be nil
  return File.basename(self.path).sub(/;[^\/]*$/, EMPTY_STR)
end

#default_portInteger

The default port for this URI’s scheme. This method will always returns the default port for the URI’s scheme regardless of the presence of an explicit port in the URI.

Returns:

  • (Integer)

    The default port.



1454
1455
1456
# File 'lib/addressable/uri.rb', line 1454

def default_port
  URI.port_mapping[self.scheme.strip.downcase] if self.scheme
end

#defer_validationObject

This method allows you to make several changes to a URI simultaneously, which separately would cause validation errors, but in conjunction, are valid. The URI will be revalidated as soon as the entire block has been executed.

Parameters:

  • block (Proc)

    A set of operations to perform on a given URI.



2396
2397
2398
2399
2400
2401
2402
2403
2404
# File 'lib/addressable/uri.rb', line 2396

def defer_validation
  raise LocalJumpError, "No block given." unless block_given?
  @validation_deferred = true
  yield
  @validation_deferred = false
  validate
ensure
  @validation_deferred = false
end

#display_uriAddressable::URI

Creates a URI suitable for display to users. If semantic attacks are likely, the application should try to detect these and warn the user. See <a href=“www.ietf.org/rfc/rfc3986.txt”>RFC 3986</a>, section 7.6 for more information.

Returns:



2201
2202
2203
2204
2205
# File 'lib/addressable/uri.rb', line 2201

def display_uri
  display_uri = self.normalize
  display_uri.host = ::Addressable::IDNA.to_unicode(display_uri.host)
  return display_uri
end

#domainObject

Returns the public suffix domain for this host.

Examples:

Addressable::URI.parse("http://www.example.co.uk").domain # => "example.co.uk"


1225
1226
1227
# File 'lib/addressable/uri.rb', line 1225

def domain
  PublicSuffix.domain(self.host, ignore_private: true)
end

#dupAddressable::URI

Clones the URI object.

Returns:



2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
# File 'lib/addressable/uri.rb', line 2271

def dup
  duplicated_uri = self.class.new(
    :scheme => self.scheme ? self.scheme.dup : nil,
    :user => self.user ? self.user.dup : nil,
    :password => self.password ? self.password.dup : nil,
    :host => self.host ? self.host.dup : nil,
    :port => self.port,
    :path => self.path ? self.path.dup : nil,
    :query => self.query ? self.query.dup : nil,
    :fragment => self.fragment ? self.fragment.dup : nil
  )
  return duplicated_uri
end

#empty?TrueClass, FalseClass

Determines if the URI is an empty string.

Returns:

  • (TrueClass, FalseClass)

    Returns true if empty, false otherwise.



2333
2334
2335
# File 'lib/addressable/uri.rb', line 2333

def empty?
  return self.to_s.empty?
end

#encode_with(coder) ⇒ Object



2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
# File 'lib/addressable/uri.rb', line 2406

def encode_with(coder)
  instance_variables.each do |ivar|
    value = instance_variable_get(ivar)
    if value != NONE
      key = ivar.to_s.slice(1..-1)
      coder[key] = value
    end
  end
  nil
end

#eql?(uri) ⇒ TrueClass, FalseClass

Returns true if the URI objects are equal. This method does NOT normalize either URI before doing the comparison.

Parameters:

  • uri (Object)

    The URI to compare.

Returns:

  • (TrueClass, FalseClass)

    true if the URIs are equivalent, false otherwise.



2253
2254
2255
2256
# File 'lib/addressable/uri.rb', line 2253

def eql?(uri)
  return false unless uri.kind_of?(URI)
  return self.to_s == uri.to_s
end

#extnameString

The extname, if any, of the file in the path component. Empty string if there is no extension.

Returns:

  • (String)

    The path’s extname.



1598
1599
1600
1601
# File 'lib/addressable/uri.rb', line 1598

def extname
  return nil unless self.path
  return File.extname(self.basename)
end

#freezeAddressable::URI

Freeze URI, initializing instance variables.

Returns:



870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'lib/addressable/uri.rb', line 870

def freeze
  self.normalized_scheme
  self.normalized_user
  self.normalized_password
  self.normalized_userinfo
  self.normalized_host
  self.normalized_port
  self.normalized_authority
  self.normalized_site
  self.normalized_path
  self.normalized_query
  self.normalized_fragment
  self.hash
  super
end

#hashInteger

A hash value that will make a URI equivalent to its normalized form.

Returns:

  • (Integer)

    A hash of the URI.



2263
2264
2265
# File 'lib/addressable/uri.rb', line 2263

def hash
  @hash ||= self.to_s.hash * -1
end

#hostnameString

This method is same as URI::Generic#host except brackets for IPv6 (and ‘IPvFuture’) addresses are removed.

Returns:

  • (String)

    The hostname for this URI.

See Also:



1178
1179
1180
1181
# File 'lib/addressable/uri.rb', line 1178

def hostname
  v = self.host
  /\A\[(.*)\]\z/ =~ v ? $1 : v
end

#hostname=(new_hostname) ⇒ Object

This method is same as URI::Generic#host= except the argument can be a bare IPv6 address (or ‘IPvFuture’).

Parameters:

  • new_hostname (String, #to_str)

    The new hostname for this URI.

See Also:



1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
# File 'lib/addressable/uri.rb', line 1190

def hostname=(new_hostname)
  if new_hostname &&
      (new_hostname.respond_to?(:ipv4?) || new_hostname.respond_to?(:ipv6?))
    new_hostname = new_hostname.to_s
  elsif new_hostname && !new_hostname.respond_to?(:to_str)
    raise TypeError, "Can't convert #{new_hostname.class} into String."
  end
  v = new_hostname ? new_hostname.to_str : nil
  v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
  self.host = v
end

#inferred_portInteger

The inferred port component for this URI. This method will normalize to the default port for the URI’s scheme if the port isn’t explicitly specified in the URI.

Returns:

  • (Integer)

    The inferred port component.



1440
1441
1442
1443
1444
1445
1446
# File 'lib/addressable/uri.rb', line 1440

def inferred_port
  if self.port.to_i == 0
    self.default_port
  else
    self.port.to_i
  end
end

#init_with(coder) ⇒ Object



2417
2418
2419
2420
2421
2422
2423
# File 'lib/addressable/uri.rb', line 2417

def init_with(coder)
  reset_ivs
  coder.map.each do |key, value|
    instance_variable_set("@#{key}", value)
  end
  nil
end

#inspectString

Returns a String representation of the URI object’s state.

Returns:

  • (String)

    The URI object’s state, as a String.



2384
2385
2386
# File 'lib/addressable/uri.rb', line 2384

def inspect
  sprintf("#<%s:%#0x URI:%s>", URI.to_s, self.object_id, self.to_s)
end

#ip_based?TrueClass, FalseClass

Determines if the scheme indicates an IP-based protocol.

Returns:

  • (TrueClass, FalseClass)

    true if the scheme indicates an IP-based protocol. false otherwise.



1855
1856
1857
1858
1859
1860
1861
# File 'lib/addressable/uri.rb', line 1855

def ip_based?
  if self.scheme
    return URI.ip_based_schemes.include?(
      self.scheme.strip.downcase)
  end
  return false
end

#join(uri) ⇒ Addressable::URI Also known as: +

Joins two URIs together.

Parameters:

Returns:



1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
# File 'lib/addressable/uri.rb', line 1889

def join(uri)
  if !uri.respond_to?(:to_str)
    raise TypeError, "Can't convert #{uri.class} into String."
  end
  if !uri.kind_of?(URI)
    # Otherwise, convert to a String, then parse.
    uri = URI.parse(uri.to_str)
  end
  if uri.to_s.empty?
    return self.dup
  end

  joined_scheme = nil
  joined_user = nil
  joined_password = nil
  joined_host = nil
  joined_port = nil
  joined_path = nil
  joined_query = nil
  joined_fragment = nil

  # Section 5.2.2 of RFC 3986
  if uri.scheme != nil
    joined_scheme = uri.scheme
    joined_user = uri.user
    joined_password = uri.password
    joined_host = uri.host
    joined_port = uri.port
    joined_path = URI.normalize_path(uri.path)
    joined_query = uri.query
  else
    if uri.authority != nil
      joined_user = uri.user
      joined_password = uri.password
      joined_host = uri.host
      joined_port = uri.port
      joined_path = URI.normalize_path(uri.path)
      joined_query = uri.query
    else
      if uri.path == nil || uri.path.empty?
        joined_path = self.path
        if uri.query != nil
          joined_query = uri.query
        else
          joined_query = self.query
        end
      else
        if uri.path[0..0] == SLASH
          joined_path = URI.normalize_path(uri.path)
        else
          base_path = self.path.dup
          base_path = EMPTY_STR if base_path == nil
          base_path = URI.normalize_path(base_path)

          # Section 5.2.3 of RFC 3986
          #
          # Removes the right-most path segment from the base path.
          if base_path.include?(SLASH)
            base_path.sub!(/\/[^\/]+$/, SLASH)
          else
            base_path = EMPTY_STR
          end

          # If the base path is empty and an authority segment has been
          # defined, use a base path of SLASH
          if base_path.empty? && self.authority != nil
            base_path = SLASH
          end

          joined_path = URI.normalize_path(base_path + uri.path)
        end
        joined_query = uri.query
      end
      joined_user = self.user
      joined_password = self.password
      joined_host = self.host
      joined_port = self.port
    end
    joined_scheme = self.scheme
  end
  joined_fragment = uri.fragment

  return self.class.new(
    :scheme => joined_scheme,
    :user => joined_user,
    :password => joined_password,
    :host => joined_host,
    :port => joined_port,
    :path => joined_path,
    :query => joined_query,
    :fragment => joined_fragment
  )
end

#join!(uri) ⇒ Addressable::URI

Destructive form of join.

Parameters:

Returns:

See Also:



1992
1993
1994
# File 'lib/addressable/uri.rb', line 1992

def join!(uri)
  replace_self(self.join(uri))
end

#merge(hash) ⇒ Addressable::URI

Merges a URI with a Hash of components. This method has different behavior from join. Any components present in the hash parameter will override the original components. The path component is not treated specially.

Parameters:

Returns:

See Also:

  • Hash#merge


2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
# File 'lib/addressable/uri.rb', line 2007

def merge(hash)
  unless hash.respond_to?(:to_hash)
    raise TypeError, "Can't convert #{hash.class} into Hash."
  end
  hash = hash.to_hash

  if hash.has_key?(:authority)
    if (hash.keys & [:userinfo, :user, :password, :host, :port]).any?
      raise ArgumentError,
        "Cannot specify both an authority and any of the components " +
        "within the authority."
    end
  end
  if hash.has_key?(:userinfo)
    if (hash.keys & [:user, :password]).any?
      raise ArgumentError,
        "Cannot specify both a userinfo and either the user or password."
    end
  end

  uri = self.class.new
  uri.defer_validation do
    # Bunch of crazy logic required because of the composite components
    # like userinfo and authority.
    uri.scheme =
      hash.has_key?(:scheme) ? hash[:scheme] : self.scheme
    if hash.has_key?(:authority)
      uri.authority =
        hash.has_key?(:authority) ? hash[:authority] : self.authority
    end
    if hash.has_key?(:userinfo)
      uri.userinfo =
        hash.has_key?(:userinfo) ? hash[:userinfo] : self.userinfo
    end
    if !hash.has_key?(:userinfo) && !hash.has_key?(:authority)
      uri.user =
        hash.has_key?(:user) ? hash[:user] : self.user
      uri.password =
        hash.has_key?(:password) ? hash[:password] : self.password
    end
    if !hash.has_key?(:authority)
      uri.host =
        hash.has_key?(:host) ? hash[:host] : self.host
      uri.port =
        hash.has_key?(:port) ? hash[:port] : self.port
    end
    uri.path =
      hash.has_key?(:path) ? hash[:path] : self.path
    uri.query =
      hash.has_key?(:query) ? hash[:query] : self.query
    uri.fragment =
      hash.has_key?(:fragment) ? hash[:fragment] : self.fragment
  end

  return uri
end

#merge!(uri) ⇒ Addressable::URI

Destructive form of merge.

Parameters:

Returns:

See Also:



2072
2073
2074
# File 'lib/addressable/uri.rb', line 2072

def merge!(uri)
  replace_self(self.merge(uri))
end

#normalizeAddressable::URI

Returns a normalized URI object.

NOTE: This method does not attempt to fully conform to specifications. It exists largely to correct other people’s failures to read the specifications, and also to deal with caching issues since several different URIs may represent the same resource and should not be cached multiple times.

Returns:



2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
# File 'lib/addressable/uri.rb', line 2164

def normalize
  # This is a special exception for the frequently misused feed
  # URI scheme.
  if normalized_scheme == "feed"
    if self.to_s =~ /^feed:\/*http:\/*/
      return URI.parse(
        self.to_s[/^feed:\/*(http:\/*.*)/, 1]
      ).normalize
    end
  end

  return self.class.new(
    :scheme => normalized_scheme,
    :authority => normalized_authority,
    :path => normalized_path,
    :query => normalized_query,
    :fragment => normalized_fragment
  )
end

#normalize!Addressable::URI

Destructively normalizes this URI object.

Returns:

See Also:



2190
2191
2192
# File 'lib/addressable/uri.rb', line 2190

def normalize!
  replace_self(self.normalize)
end

#normalized_authorityString

The authority component for this URI, normalized.

Returns:

  • (String)

    The authority component, normalized.



1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
# File 'lib/addressable/uri.rb', line 1252

def normalized_authority
  return nil unless self.authority
  @normalized_authority ||= begin
    authority = String.new
    if self.normalized_userinfo != nil
      authority << "#{self.normalized_userinfo}@"
    end
    authority << self.normalized_host
    if self.normalized_port != nil
      authority << ":#{self.normalized_port}"
    end
    authority
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_authority)
  @normalized_authority
end

#normalized_fragmentString

The fragment component for this URI, normalized.

Returns:

  • (String)

    The fragment component, normalized.



1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
# File 'lib/addressable/uri.rb', line 1816

def normalized_fragment
  return nil unless self.fragment
  return @normalized_fragment unless @normalized_fragment == NONE
  @normalized_fragment = begin
    component = Addressable::URI.normalize_component(
      self.fragment,
      Addressable::URI::NormalizeCharacterClasses::FRAGMENT
    )
    component == "" ? nil : component
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_fragment)
  @normalized_fragment
end

#normalized_hostString

The host component for this URI, normalized.

Returns:

  • (String)

    The host component, normalized.



1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
# File 'lib/addressable/uri.rb', line 1126

def normalized_host
  return nil unless self.host

  @normalized_host ||= begin
    if !self.host.strip.empty?
      result = ::Addressable::IDNA.to_ascii(
        URI.unencode_component(self.host.strip.downcase)
      )
      if result =~ /[^\.]\.$/
        # Single trailing dots are unnecessary.
        result = result[0...-1]
      end
      result = Addressable::URI.normalize_component(
        result,
        NormalizeCharacterClasses::HOST
      )
      result
    else
      EMPTY_STR.dup
    end
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_host)
  @normalized_host
end

#normalized_passwordString

The password component for this URI, normalized.

Returns:

  • (String)

    The password component, normalized.



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/addressable/uri.rb', line 1002

def normalized_password
  return nil unless self.password
  return @normalized_password unless @normalized_password == NONE
  @normalized_password = begin
    if self.normalized_scheme =~ /https?/ && self.password.strip.empty? &&
        (!self.user || self.user.strip.empty?)
      nil
    else
      Addressable::URI.normalize_component(
        self.password.strip,
        Addressable::URI::NormalizeCharacterClasses::UNRESERVED
      )
    end
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_password)
  @normalized_password
end

#normalized_pathString

The path component for this URI, normalized.

Returns:

  • (String)

    The path component, normalized.



1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
# File 'lib/addressable/uri.rb', line 1535

def normalized_path
  @normalized_path ||= begin
    path = self.path.to_s
    if self.scheme == nil && path =~ NORMPATH
      # Relative paths with colons in the first segment are ambiguous.
      path = path.sub(":", "%2F")
    end
    # String#split(delimeter, -1) uses the more strict splitting behavior
    # found by default in Python.
    result = path.strip.split(SLASH, -1).map do |segment|
      Addressable::URI.normalize_component(
        segment,
        Addressable::URI::NormalizeCharacterClasses::PCHAR
      )
    end.join(SLASH)

    result = URI.normalize_path(result)
    if result.empty? &&
        ["http", "https", "ftp", "tftp"].include?(self.normalized_scheme)
      result = SLASH.dup
    end
    result
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_path)
  @normalized_path
end

#normalized_portInteger

The port component for this URI, normalized.

Returns:

  • (Integer)

    The port component, normalized.



1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
# File 'lib/addressable/uri.rb', line 1392

def normalized_port
  return nil unless self.port
  return @normalized_port unless @normalized_port == NONE
  @normalized_port = begin
    if URI.port_mapping[self.normalized_scheme] == self.port
      nil
    else
      self.port
    end
  end
end

#normalized_query(*flags) ⇒ String

The query component for this URI, normalized.

Returns:

  • (String)

    The query component, normalized.



1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
# File 'lib/addressable/uri.rb', line 1613

def normalized_query(*flags)
  return nil unless self.query
  return @normalized_query unless @normalized_query == NONE
  @normalized_query = begin
    modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup
    # Make sure possible key-value pair delimiters are escaped.
    modified_query_class.sub!("\\&", "").sub!("\\;", "")
    pairs = (query || "").split("&", -1)
    pairs.delete_if(&:empty?).uniq! if flags.include?(:compacted)
    pairs.sort! if flags.include?(:sorted)
    component = pairs.map do |pair|
      Addressable::URI.normalize_component(
        pair,
        Addressable::URI::NormalizeCharacterClasses::QUERY,
        "+"
      )
    end.join("&")
    component == "" ? nil : component
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_query)
  @normalized_query
end

#normalized_schemeString

The scheme component for this URI, normalized.

Returns:

  • (String)

    The scheme component, normalized.



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# File 'lib/addressable/uri.rb', line 896

def normalized_scheme
  return nil unless self.scheme
  if @normalized_scheme == NONE
    @normalized_scheme = if self.scheme =~ /^\s*ssh\+svn\s*$/i
      "svn+ssh".dup
    else
      Addressable::URI.normalize_component(
        self.scheme.strip.downcase,
        Addressable::URI::NormalizeCharacterClasses::SCHEME
      )
    end
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_scheme)
  @normalized_scheme
end

#normalized_siteString

The normalized combination of components that represent a site. Combines the scheme, user, password, host, and port components. Primarily useful for HTTP and HTTPS.

For example, "http://example.com/path?query" would have a site value of "http://example.com".

Returns:

  • (String)

    The normalized components that identify a site.



1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
# File 'lib/addressable/uri.rb', line 1485

def normalized_site
  return nil unless self.site
  @normalized_site ||= begin
    site_string = "".dup
    if self.normalized_scheme != nil
      site_string << "#{self.normalized_scheme}:"
    end
    if self.normalized_authority != nil
      site_string << "//#{self.normalized_authority}"
    end
    site_string
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_site)
  @normalized_site
end

#normalized_userString

The user component for this URI, normalized.

Returns:

  • (String)

    The user component, normalized.



947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/addressable/uri.rb', line 947

def normalized_user
  return nil unless self.user
  return @normalized_user unless @normalized_user == NONE
  @normalized_user = begin
    if normalized_scheme =~ /https?/ && self.user.strip.empty? &&
        (!self.password || self.password.strip.empty?)
      nil
    else
      Addressable::URI.normalize_component(
        self.user.strip,
        Addressable::URI::NormalizeCharacterClasses::UNRESERVED
      )
    end
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_user)
  @normalized_user
end

#normalized_userinfoString

The userinfo component for this URI, normalized.

Returns:

  • (String)

    The userinfo component, normalized.



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
# File 'lib/addressable/uri.rb', line 1068

def normalized_userinfo
  return nil unless self.userinfo
  return @normalized_userinfo unless @normalized_userinfo == NONE
  @normalized_userinfo = begin
    current_user = self.normalized_user
    current_password = self.normalized_password
    if !current_user && !current_password
      nil
    elsif current_user && current_password
      "#{current_user}:#{current_password}".dup
    elsif current_user && !current_password
      "#{current_user}".dup
    end
  end
  # All normalized values should be UTF-8
  force_utf8_encoding_if_needed(@normalized_userinfo)
  @normalized_userinfo
end

#omit(*components) ⇒ Addressable::URI

Omits components from a URI.

Examples:

uri = Addressable::URI.parse("http://example.com/path?query")
#=> #<Addressable::URI:0xcc5e7a URI:http://example.com/path?query>
uri.omit(:scheme, :authority)
#=> #<Addressable::URI:0xcc4d86 URI:/path?query>

Parameters:

  • *components (Symbol)

    The components to be omitted.

Returns:



2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
# File 'lib/addressable/uri.rb', line 2297

def omit(*components)
  invalid_components = components - [
    :scheme, :user, :password, :userinfo, :host, :port, :authority,
    :path, :query, :fragment
  ]
  unless invalid_components.empty?
    raise ArgumentError,
      "Invalid component names: #{invalid_components.inspect}."
  end
  duplicated_uri = self.dup
  duplicated_uri.defer_validation do
    components.each do |component|
      duplicated_uri.send((component.to_s + "=").to_sym, nil)
    end
    duplicated_uri.user = duplicated_uri.normalized_user
  end
  duplicated_uri
end

#omit!(*components) ⇒ Addressable::URI

Destructive form of omit.

Parameters:

  • *components (Symbol)

    The components to be omitted.

Returns:

See Also:



2324
2325
2326
# File 'lib/addressable/uri.rb', line 2324

def omit!(*components)
  replace_self(self.omit(*components))
end

#originString

The origin for this URI, serialized to ASCII, as per RFC 6454, section 6.2.

Returns:

  • (String)

    The serialized origin.



1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
# File 'lib/addressable/uri.rb', line 1314

def origin
  if self.scheme && self.authority
    if self.normalized_port
      "#{self.normalized_scheme}://#{self.normalized_host}" +
      ":#{self.normalized_port}"
    else
      "#{self.normalized_scheme}://#{self.normalized_host}"
    end
  else
    "null"
  end
end

#origin=(new_origin) ⇒ Object

Sets the origin for this URI, serialized to ASCII, as per RFC 6454, section 6.2. This assignment will reset the ‘userinfo` component.

Parameters:

  • new_origin (String, #to_str)

    The new origin component.



1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
# File 'lib/addressable/uri.rb', line 1333

def origin=(new_origin)
  if new_origin
    if !new_origin.respond_to?(:to_str)
      raise TypeError, "Can't convert #{new_origin.class} into String."
    end
    new_origin = new_origin.to_str
    new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1]
    unless new_scheme
      raise InvalidURIError, 'An origin cannot omit the scheme.'
    end
    new_host = new_origin[/:\/\/([^\/?#:]+)/, 1]
    unless new_host
      raise InvalidURIError, 'An origin cannot omit the host.'
    end
    new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1]
  end

  self.scheme = new_scheme
  self.host = new_host
  self.port = new_port
  self.userinfo = nil

  # Reset dependent values
  @userinfo = nil
  @normalized_userinfo = NONE
  @authority = nil
  @normalized_authority = nil
  remove_composite_values

  # Ensure we haven't created an invalid URI
  validate()
end

#query_values(return_type = Hash) ⇒ Hash, ...

Converts the query component to a Hash value.

Examples:

Addressable::URI.parse("?one=1&two=2&three=3").query_values
#=> {"one" => "1", "two" => "2", "three" => "3"}
Addressable::URI.parse("?one=two&one=three").query_values(Array)
#=> [["one", "two"], ["one", "three"]]
Addressable::URI.parse("?one=two&one=three").query_values(Hash)
#=> {"one" => "three"}
Addressable::URI.parse("?").query_values
#=> {}
Addressable::URI.parse("").query_values
#=> nil

Parameters:

  • return_type (Class) (defaults to: Hash)

    The return type desired. Value must be either ‘Hash` or `Array`.

Returns:

  • (Hash, Array, nil)

    The query string parsed as a Hash or Array or nil if the query string is blank.



1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
# File 'lib/addressable/uri.rb', line 1672

def query_values(return_type=Hash)
  empty_accumulator = Array == return_type ? [] : {}
  if return_type != Hash && return_type != Array
    raise ArgumentError, "Invalid return type. Must be Hash or Array."
  end
  return nil if self.query == nil
  split_query = self.query.split("&").map do |pair|
    pair.split("=", 2) if pair && !pair.empty?
  end.compact
  return split_query.inject(empty_accumulator.dup) do |accu, pair|
    # I'd rather use key/value identifiers instead of array lookups,
    # but in this case I really want to maintain the exact pair structure,
    # so it's best to make all changes in-place.
    pair[0] = URI.unencode_component(pair[0])
    if pair[1].respond_to?(:to_str)
      value = pair[1].to_str
      # I loathe the fact that I have to do this. Stupid HTML 4.01.
      # Treating '+' as a space was just an unbelievably bad idea.
      # There was nothing wrong with '%20'!
      # If it ain't broke, don't fix it!
      value = value.tr("+", " ") if ["http", "https", nil].include?(scheme)
      pair[1] = URI.unencode_component(value)
    end
    if return_type == Hash
      accu[pair[0]] = pair[1]
    else
      accu << pair
    end
    accu
  end
end

#query_values=(new_query_values) ⇒ Object

Sets the query component for this URI from a Hash object. An empty Hash or Array will result in an empty query string.

Examples:

uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b=c&b=d&b=e"
uri.query_values = [['a', 'a'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
uri.query
# => "a=a&b=c&b=d&b=e"
uri.query_values = [['a', 'a'], ['b', ['c', 'd', 'e']]]
uri.query
# => "a=a&b=c&b=d&b=e"
uri.query_values = [['flag'], ['key', 'value']]
uri.query
# => "flag&key=value"

Parameters:

  • new_query_values (Hash, #to_hash, Array)

    The new query values.



1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
# File 'lib/addressable/uri.rb', line 1723

def query_values=(new_query_values)
  if new_query_values == nil
    self.query = nil
    return nil
  end

  if !new_query_values.is_a?(Array)
    if !new_query_values.respond_to?(:to_hash)
      raise TypeError,
        "Can't convert #{new_query_values.class} into Hash."
    end
    new_query_values = new_query_values.to_hash
    new_query_values = new_query_values.map do |key, value|
      key = key.to_s if key.kind_of?(Symbol)
      [key, value]
    end
    # Useful default for OAuth and caching.
    # Only to be used for non-Array inputs. Arrays should preserve order.
    new_query_values.sort!
  end

  # new_query_values have form [['key1', 'value1'], ['key2', 'value2']]
  buffer = "".dup
  new_query_values.each do |key, value|
    encoded_key = URI.encode_component(
      key, CharacterClassesRegexps::UNRESERVED
    )
    if value == nil
      buffer << "#{encoded_key}&"
    elsif value.kind_of?(Array)
      value.each do |sub_value|
        encoded_value = URI.encode_component(
          sub_value, CharacterClassesRegexps::UNRESERVED
        )
        buffer << "#{encoded_key}=#{encoded_value}&"
      end
    else
      encoded_value = URI.encode_component(
        value, CharacterClassesRegexps::UNRESERVED
      )
      buffer << "#{encoded_key}=#{encoded_value}&"
    end
  end
  self.query = buffer.chop
end

#relative?TrueClass, FalseClass

Determines if the URI is relative.

Returns:

  • (TrueClass, FalseClass)

    true if the URI is relative. false otherwise.



1869
1870
1871
# File 'lib/addressable/uri.rb', line 1869

def relative?
  return self.scheme.nil?
end

#request_uriString

The HTTP request URI for this URI. This is the path and the query string.

Returns:

  • (String)

    The request URI required for an HTTP request.



1774
1775
1776
1777
1778
1779
1780
# File 'lib/addressable/uri.rb', line 1774

def request_uri
  return nil if self.absolute? && self.scheme !~ /^https?$/i
  return (
    (!self.path.empty? ? self.path : SLASH) +
    (self.query ? "?#{self.query}" : EMPTY_STR)
  )
end

#request_uri=(new_request_uri) ⇒ Object

Sets the HTTP request URI for this URI.

Parameters:

  • new_request_uri (String, #to_str)

    The new HTTP request URI.



1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
# File 'lib/addressable/uri.rb', line 1786

def request_uri=(new_request_uri)
  if !new_request_uri.respond_to?(:to_str)
    raise TypeError, "Can't convert #{new_request_uri.class} into String."
  end
  if self.absolute? && self.scheme !~ /^https?$/i
    raise InvalidURIError,
      "Cannot set an HTTP request URI for a non-HTTP URI."
  end
  new_request_uri = new_request_uri.to_str
  path_component = new_request_uri[/^([^\?]*)\??(?:.*)$/, 1]
  query_component = new_request_uri[/^(?:[^\?]*)\?(.*)$/, 1]
  path_component = path_component.to_s
  path_component = (!path_component.empty? ? path_component : SLASH)
  self.path = path_component
  self.query = query_component

  # Reset dependent values
  remove_composite_values
end

#route_from(uri) ⇒ Addressable::URI

Returns the shortest normalized relative form of this URI that uses the supplied URI as a base for resolution. Returns an absolute URI if necessary. This is effectively the opposite of route_to.

Parameters:

Returns:

  • (Addressable::URI)

    The normalized relative URI that is equivalent to the original URI.



2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
# File 'lib/addressable/uri.rb', line 2085

def route_from(uri)
  uri = URI.parse(uri).normalize
  normalized_self = self.normalize
  if normalized_self.relative?
    raise ArgumentError, "Expected absolute URI, got: #{self.to_s}"
  end
  if uri.relative?
    raise ArgumentError, "Expected absolute URI, got: #{uri.to_s}"
  end
  if normalized_self == uri
    return Addressable::URI.parse("##{normalized_self.fragment}")
  end
  components = normalized_self.to_hash
  if normalized_self.scheme == uri.scheme
    components[:scheme] = nil
    if normalized_self.authority == uri.authority
      components[:user] = nil
      components[:password] = nil
      components[:host] = nil
      components[:port] = nil
      if normalized_self.path == uri.path
        components[:path] = nil
        if normalized_self.query == uri.query
          components[:query] = nil
        end
      else
        if uri.path != SLASH and components[:path]
          self_splitted_path = split_path(components[:path])
          uri_splitted_path = split_path(uri.path)
          self_dir = self_splitted_path.shift
          uri_dir = uri_splitted_path.shift
          while !self_splitted_path.empty? && !uri_splitted_path.empty? and self_dir == uri_dir
            self_dir = self_splitted_path.shift
            uri_dir = uri_splitted_path.shift
          end
          components[:path] = (uri_splitted_path.fill('..') + [self_dir] + self_splitted_path).join(SLASH)
        end
      end
    end
  end
  # Avoid network-path references.
  if components[:host] != nil
    components[:scheme] = normalized_self.scheme
  end
  return Addressable::URI.new(
    :scheme => components[:scheme],
    :user => components[:user],
    :password => components[:password],
    :host => components[:host],
    :port => components[:port],
    :path => components[:path],
    :query => components[:query],
    :fragment => components[:fragment]
  )
end

#route_to(uri) ⇒ Addressable::URI

Returns the shortest normalized relative form of the supplied URI that uses this URI as a base for resolution. Returns an absolute URI if necessary. This is effectively the opposite of route_from.

Parameters:

Returns:

  • (Addressable::URI)

    The normalized relative URI that is equivalent to the supplied URI.



2150
2151
2152
# File 'lib/addressable/uri.rb', line 2150

def route_to(uri)
  return URI.parse(uri).route_from(self)
end

#siteString

The combination of components that represent a site. Combines the scheme, user, password, host, and port components. Primarily useful for HTTP and HTTPS.

For example, "http://example.com/path?query" would have a site value of "http://example.com".

Returns:

  • (String)

    The components that identify a site.



1467
1468
1469
1470
1471
1472
1473
1474
# File 'lib/addressable/uri.rb', line 1467

def site
  (self.scheme || self.authority) && @site ||= begin
    site_string = "".dup
    site_string << "#{self.scheme}:" if self.scheme != nil
    site_string << "//#{self.authority}" if self.authority != nil
    site_string
  end
end

#site=(new_site) ⇒ Object

Sets the site value for this URI.

Parameters:

  • new_site (String, #to_str)

    The new site value.



1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
# File 'lib/addressable/uri.rb', line 1506

def site=(new_site)
  if new_site
    if !new_site.respond_to?(:to_str)
      raise TypeError, "Can't convert #{new_site.class} into String."
    end
    new_site = new_site.to_str
    # These two regular expressions derived from the primary parsing
    # expression
    self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1]
    self.authority = new_site[
      /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1
    ]
  else
    self.scheme = nil
    self.authority = nil
  end
end

#tldObject

Returns the top-level domain for this host.

Examples:

Addressable::URI.parse("http://www.example.co.uk").tld # => "co.uk"


1207
1208
1209
# File 'lib/addressable/uri.rb', line 1207

def tld
  PublicSuffix.parse(self.host, ignore_private: true).tld
end

#tld=(new_tld) ⇒ Object

Sets the top-level domain for this URI.

Parameters:

  • new_tld (String, #to_str)

    The new top-level domain.



1215
1216
1217
1218
# File 'lib/addressable/uri.rb', line 1215

def tld=(new_tld)
  replaced_tld = host.sub(/#{tld}\z/, new_tld)
  self.host = PublicSuffix::Domain.new(replaced_tld).to_s
end

#to_hashHash

Returns a Hash of the URI components.

Returns:

  • (Hash)

    The URI as a Hash of components.



2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
# File 'lib/addressable/uri.rb', line 2367

def to_hash
  return {
    :scheme => self.scheme,
    :user => self.user,
    :password => self.password,
    :host => self.host,
    :port => self.port,
    :path => self.path,
    :query => self.query,
    :fragment => self.fragment
  }
end

#to_sString Also known as: to_str

Converts the URI to a String.

Returns:

  • (String)

    The URI’s String representation.



2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
# File 'lib/addressable/uri.rb', line 2341

def to_s
  if self.scheme == nil && self.path != nil && !self.path.empty? &&
      self.path =~ NORMPATH
    raise InvalidURIError,
      "Cannot assemble URI string with ambiguous path: '#{self.path}'"
  end
  @uri_string ||= begin
    uri_string = String.new
    uri_string << "#{self.scheme}:" if self.scheme != nil
    uri_string << "//#{self.authority}" if self.authority != nil
    uri_string << self.path.to_s
    uri_string << "?#{self.query}" if self.query != nil
    uri_string << "##{self.fragment}" if self.fragment != nil
    uri_string.force_encoding(Encoding::UTF_8)
    uri_string
  end
end

#userinfoString

The userinfo component for this URI. Combines the user and password components.

Returns:

  • (String)

    The userinfo component.



1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
# File 'lib/addressable/uri.rb', line 1052

def userinfo
  current_user = self.user
  current_password = self.password
  (current_user || current_password) && @userinfo ||= begin
    if current_user && current_password
      "#{current_user}:#{current_password}"
    elsif current_user && !current_password
      "#{current_user}"
    end
  end
end

#userinfo=(new_userinfo) ⇒ Object

Sets the userinfo component for this URI.

Parameters:

  • new_userinfo (String, #to_str)

    The new userinfo component.



1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
# File 'lib/addressable/uri.rb', line 1091

def userinfo=(new_userinfo)
  if new_userinfo && !new_userinfo.respond_to?(:to_str)
    raise TypeError, "Can't convert #{new_userinfo.class} into String."
  end
  new_user, new_password = if new_userinfo
    [
      new_userinfo.to_str.strip[/^(.*):/, 1],
      new_userinfo.to_str.strip[/:(.*)$/, 1]
    ]
  else
    [nil, nil]
  end

  # Password assigned first to ensure validity in case of nil
  self.password = new_password
  self.user = new_user

  # Reset dependent values
  @authority = nil
  remove_composite_values

  # Ensure we haven't created an invalid URI
  validate()
end