ERB's url_encode http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB/Util.html#method-c-url_encode可以调整:
def url_encode(s)
s.to_s.dup.force_encoding("ASCII-8BIT").gsub(%r[^a-zA-Z0-9_\-.]/) {
sprintf("%%%02X", $&.unpack("C")[0])
}
end
to:
def url_encode(s, regex=%r[^a-zA-Z0-9_\-.]/)
s.to_s.dup.force_encoding("ASCII-8BIT").gsub(regex) {
sprintf("%%%02X", $&.unpack("C")[0])
}
end
url_encode('pop', /./)
=> "%70%6F%70"
此外,Ruby 的 CGI 和 URI 模块能够对 URL 进行编码,将受限制的字符转换为实体,因此不要忽视它们的功能。
例如,URL 参数的转义字符:
CGI.escape('http://www.example.com')
=> "http%3A%2F%2Fwww.example.com"
CGI.escape('<body><p>foo</p></body>')
=> "%3Cbody%3E%3Cp%3Efoo%3C%2Fp%3E%3C%2Fbody%3E"
Ruby CGI 的escape http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html#method-c-escapeElement还使用一个小正则表达式来确定 URL 中哪些字符应该转义。这是文档中该方法的定义:
def CGI::escape(string)
string.gsub(%r([^ a-zA-Z0-9_.-]+)/) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end.tr(' ', '+')
end
您还可以覆盖它并更改正则表达式,或者在方法的重新定义中将其公开以供您自己使用:
def CGI::escape(string, escape_regex=%r([^ a-zA-Z0-9_.-]+)/)
string.gsub(escape_regex) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end.tr(' ', '+')
end
URI.encode_www_form_component http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html#method-c-encode_www_form也做了类似的编码,字符上的唯一区别是*
and
:
URI.encode_www_form_component('<p>foo</p>')
=> "%3Cp%3Efoo%3C%2Fp%3E"
并且,与覆盖类似CGI::escape
,您可以覆盖中的正则表达式URI.encode_www_form_component
:
def self.encode_www_form_component(str, regex=%r[^*\-.0-9A-Z_a-z]/)
str = str.to_s
if HTML5ASCIIINCOMPAT.include?(str.encoding)
str = str.encode(Encoding::UTF_8)
else
str = str.dup
end
str.force_encoding(Encoding::ASCII_8BIT)
str.gsub!(regex, TBLENCWWWCOMP_)
str.force_encoding(Encoding::US_ASCII)
end