How to transform text with characters to HTML Entities with Ruby on Rails?
I Want to use an URL to call a method but i need it to be written with HTML Entities:
so if i开发者_如何学运维 have http://www.myurl.com/foobar
for example using a Ruby on Rails helper i can get something like:
http%3A%2F%2Fwww.myurl.com%2Ffoobar
I don't know if there's anything built directly into rails to do all of that escaping, but if you require 'cgi'
you can use CGI::escape
.
ruby-1.8.7-p174 :001 > require 'cgi'
=> true
ruby-1.8.7-p174 :002 > s = "http://www.myurl.com/foobar"
=> "http://www.myurl.com/foobar"
ruby-1.8.7-p174 :003 > CGI::escape(s)
=> "http%3A%2F%2Fwww.myurl.com%2Ffoobar"
Obviously, to make it look a little nicer in your views, or wherever, you could wrap that method in a helper.
there is the great rubygem "htmlentities" which does the trick: http://htmlentities.rubyforge.org/
精彩评论