I'm trying to convert a url string into a label for a Google Chart.
My question is this: my input is something like www.mysite.com/link
and it needs to be encoded so it can itself be embedded into the Google charts URL.
Before: www.mysite.com/link/test
After: www.mysite.com%2Flink%2Ftest
How can I convert a regular string into a UTF-8 URL-encoded stri开发者_运维技巧ng in Rails?
There's also CGI.escape
from the standard library:
>> CGI.escape('www.mysite.com/link/test')
=> "www.mysite.com%2Flink%2Ftest"
Rails 3.0 is based on Rack, Rack provides a Rack::Utils.escape method.
s = "www.mysite.com/link/test"
# => "www.mysite.com/link/test
Rack::Utils.escape(s)
# => "www.mysite.com%2Flink%2Ftest"
#saved in ./lib/string.rb
class String
def encode_this
self.gsub(' ', '%20').gsub('/', '%2F') #etc...
end
end
This would be universal and customizable for your needs.
"www.mysite.com/link/test".encode_this
=> "www.mysite.com%2Flink%2Ftest"
精彩评论