2016-02-01 15:43:26 +03:00
|
|
|
# frozen_string_literal: true
|
2013-10-16 04:14:16 +04:00
|
|
|
require 'cgi'
|
2013-07-10 03:21:36 +04:00
|
|
|
require 'uri'
|
|
|
|
|
2013-10-20 05: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-10 03:21:36 +04:00
|
|
|
class Gem::UriFormatter
|
2013-10-20 05:33:19 +04:00
|
|
|
|
|
|
|
##
|
|
|
|
# The URI to be formatted.
|
|
|
|
|
2013-07-10 03:21:36 +04:00
|
|
|
attr_reader :uri
|
|
|
|
|
2013-10-20 05:33:19 +04:00
|
|
|
##
|
|
|
|
# Creates a new URI formatter for +uri+.
|
|
|
|
|
2013-07-10 03:21:36 +04:00
|
|
|
def initialize uri
|
|
|
|
@uri = uri
|
|
|
|
end
|
|
|
|
|
2013-10-20 05:33:19 +04:00
|
|
|
##
|
|
|
|
# Escapes the #uri for use as a CGI parameter
|
|
|
|
|
2013-07-10 03:21:36 +04:00
|
|
|
def escape
|
|
|
|
return unless @uri
|
2013-10-16 04:14:16 +04:00
|
|
|
CGI.escape @uri
|
2013-07-10 03: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-20 05:33:19 +04:00
|
|
|
##
|
|
|
|
# Unescapes the #uri which came from a CGI parameter
|
|
|
|
|
2013-07-10 03:21:36 +04:00
|
|
|
def unescape
|
|
|
|
return unless @uri
|
2013-10-16 04:14:16 +04:00
|
|
|
CGI.unescape @uri
|
2013-07-10 03:21:36 +04:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|