2015-12-16 00:07:31 -05:00
|
|
|
# frozen_string_literal: false
|
2013-10-15 20:14:16 -04:00
|
|
|
require 'cgi'
|
2013-07-09 19:21:36 -04:00
|
|
|
require 'uri'
|
|
|
|
|
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+.
|
|
|
|
|
2013-07-09 19:21:36 -04:00
|
|
|
def initialize uri
|
|
|
|
@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
|
|
|
|
|