summaryrefslogtreecommitdiff
path: root/jni/ruby/lib/rubygems/uri_formatter.rb
blob: 68aacc6369cbc317ff88b254ea9e0d715f90a221 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'cgi'
require 'uri'

##
# The UriFormatter handles URIs from user-input and escaping.
#
#   uf = Gem::UriFormatter.new 'example.com'
#
#   p uf.normalize #=> 'http://example.com'

class Gem::UriFormatter

  ##
  # The URI to be formatted.

  attr_reader :uri

  ##
  # Creates a new URI formatter for +uri+.

  def initialize uri
    @uri = uri
  end

  ##
  # Escapes the #uri for use as a CGI parameter

  def escape
    return unless @uri
    CGI.escape @uri
  end

  ##
  # Normalize the URI by adding "http://" if it is missing.

  def normalize
    (@uri =~ /^(https?|ftp|file):/i) ? @uri : "http://#{@uri}"
  end

  ##
  # Unescapes the #uri which came from a CGI parameter

  def unescape
    return unless @uri
    CGI.unescape @uri
  end

end