ruby-on-rails – 为什么当ActionView :: OutputBuffer调用时,URI.escape失败?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 为什么当ActionView :: OutputBuffer调用时,URI.escape失败?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我将应用程序从Rails 2升级到Rails 3.显然,调用render()现在返回ActionView :: OutputBuffer而不是String.我需要将render()的结果传递给URI.escape(),并且此异常失败…

这是我在控制台中的简短测试

ob = ActionView::OutputBuffer.new("test test")
URI.escape(ob)
    `NoMethodError: undefined method 'each_byte' for nil:NilClass`. 
        from /opt/ruby19/lib/ruby/1.9.1/uri/common.rb:307:in `block in escape'
        from ..../ruby/1.9.1/gems/activesupport-3.2.1/lib/active_support/core_ext/string/output_safety.rb:160:in `gsub'
        from ..../ruby/1.9.1/gems/activesupport-3.2.1/lib/active_support/core_ext/string/output_safety.rb:160:in `gsub'
        from /opt/ruby19/lib/ruby/1.9.1/uri/common.rb:304:in `escape'
        from /opt/ruby19/lib/ruby/1.9.1/uri/common.rb:623:in `escape'

此外,在OutputBuffer上调用to_s返回相同的OutputBuffer类,所以我甚至不能将此缓冲区转换成一个诚实的字符串?

ob.to_s.class 
    ActionView::OutputBuffer

当然,调用URI.escape(“test test”)会按预期的方式返回“test test”,所以这不是URI问题.

环境:

> ruby​​ 1.9.3p125(2012-02-16修订版34643)[i686-linux]
> Rails 3.2.1

我的问题是:为什么这样会发生,我该如何解决这个问题?

更新:显然,使用ob作为ob.to_s的形式将OutputBuffer转换为String,这有效地解决了问题.但是我的问题“为什么会发生”仍然存在,例如这是一个错误,我应该报告,还是我做错了?

解决方法

@H_403_24@ 这是 bug in Rails

When calling gsub with a block on an ActiveSupport::SafeBuffer the global variables $1,$2,etc. for referencing submatches are not always properly set (anymore?) when the block is called.

这就是为什么URI.escape(和使用gsub()的任何其他函数会在ActiveSupprt :: Safebuffer上失败.

现在有several discussions,显然现在最安全的路由是在将SafeBuffer传递给任何可以调用gsub的内容之前调用to_str,例如URI.encode,escape_javascript和类似的功能.

关于to_s返回相同类的其他问题 – 显然安全的缓冲区会自动返回,而不是一个裸字符串,这是设计的.为了获得一个真正的字符串,可以使用.to_str.

原文链接:https://www.f2er.com/ruby/271775.html

猜你在找的Ruby相关文章