2016-02-01 07:43:26 -05:00
|
|
|
# frozen_string_literal: true
|
2013-07-09 19:21:36 -04:00
|
|
|
|
2013-10-19 21:33:19 -04:00
|
|
|
##
|
|
|
|
# The UriFormatter handles URIs from user-input and escaping.
|
|
|
|
#
|
|
|
|
# uf = Gem::UriFormatter.new 'example.com'
|
|
|
|
#
|
|
|
|
# p uf.normalize #=> 'http://example.com'
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
class Gem::UriFormatter
|
2013-10-19 21:33:19 -04:00
|
|
|
##
|
|
|
|
# The URI to be formatted.
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
attr_reader :uri
|
|
|
|
|
2013-10-19 21:33:19 -04:00
|
|
|
##
|
|
|
|
# Creates a new URI formatter for +uri+.
|
|
|
|
|
2018-11-21 05:20:47 -05:00
|
|
|
def initialize(uri)
|
2020-12-08 02:33:39 -05:00
|
|
|
require 'cgi'
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
@uri = uri
|
|
|
|
end
|
|
|
|
|
2013-10-19 21:33:19 -04:00
|
|
|
##
|
|
|
|
# Escapes the #uri for use as a CGI parameter
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
def escape
|
|
|
|
return unless @uri
|
2013-10-15 20:14:16 -04:00
|
|
|
CGI.escape @uri
|
2013-07-09 19:21:36 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
##
|
|
|
|
# Normalize the URI by adding "http://" if it is missing.
|
|
|
|
|
|
|
|
def normalize
|
|
|
|
(@uri =~ /^(https?|ftp|file):/i) ? @uri : "http://#{@uri}"
|
|
|
|
end
|
|
|
|
|
2013-10-19 21:33:19 -04:00
|
|
|
##
|
|
|
|
# Unescapes the #uri which came from a CGI parameter
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
def unescape
|
|
|
|
return unless @uri
|
2013-10-15 20:14:16 -04:00
|
|
|
CGI.unescape @uri
|
2013-07-09 19:21:36 -04:00
|
|
|
end
|
|
|
|
end
|