2011-06-23 111 views
5

我有一些内容(HTML)正被编码为这个JavaScript(由this page)的结果,发到我的Rails应用程序:ruby​​/rails相当于javascript decodeURIComponent?

function encode_utf8_b64(string) { 
return window.btoa(unescape(encodeURIComponent(string))); 
} 

的对应的js代码,让它回到原来是这样的:

function decode_utf8_b64(string) { 
return decodeURIComponent(escape(window.atob(string))); 
} 

我的问题是,是否有相当于ruby的decodeURIComponent()?到目前为止,我有这一点,得到它的出路的一部分,但我错过decodeURIComponent的最后一步:

CGI::escape(Base64.decode64(string)) 

回答

12

URI.unescape或许可以帮助:

def decode_utf8_b64(string) 
    URI.unescape(CGI::escape(Base64.decode64(string))) 
end 

你必须添加必要的rubygem太:

require 'uri' 

我已经测试了这个红宝石1.9.2。

+0

thx,我已经更新了答案:) – olistik

+0

谢谢 - 当我应用URI.unescape或URI.decode时,我得到一个“UTF-8中无效的字节序列”错误。看起来CGI :: escape()的输出是US-ASCII。当我尝试使用Iconv在应用URI.unescape之前将字符串转换为UTF-8时,它停止抛出错误,但似乎只是删除了一个解码步骤,因此输出仍然很乱。有小费吗?或者,也许这是一个单独的问题。 – bobfet1