url_encode in Ruby

别来无恙 提交于 2019-12-12 08:34:11

问题


I read the documentation of url_encode.

Is there a table that tells me exactly which character is encoded to what, using url_encode?


回答1:


ERB's url_encode can be tweaked:

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"

In addition, Ruby's CGI and URI modules have the ability to encode URLs, converting restricted characters to entities, so don't overlook their offerings.

For instance, escaping characters for URL parameters:

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's escape also uses a small regex to figure out which characters should be escaped in a URL. This is the method's definition from the documentation:

def CGI::escape(string)
  string.gsub(%r([^ a-zA-Z0-9_.-]+)/) do
    '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
  end.tr(' ', '+')
end

You also override that and change the regex, or expose it for your own use inside your redefinition of the method:

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 also does a similar encoding, the only differences in characters are * and :

URI.encode_www_form_component('<p>foo</p>')
=> "%3Cp%3Efoo%3C%2Fp%3E"

And, similarly to overriding CGI::escape, you can override the regex in 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


来源:https://stackoverflow.com/questions/13338672/url-encode-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!