gpt4 book ai didi

ruby-on-rails - 为什么在 ActionView::OutputBuffer 上调用 URI.escape 会失败?

转载 作者:行者123 更新时间:2023-12-03 21:48:25 24 4
gpt4 key购买 nike

我正在将应用程序从 Rails 2 升级到 Rails 3。显然,调用 render()现在返回 ActionView::OutputBuffer而不是 String .我需要传递render()的结果至 URI.escape() ,这失败了,但有异常(exception)......

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

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%20test",所以这不是 URI 问题。

环境:
  • ruby 1.9.3p125 (2012-02-16 修订版 34643) [i686-linux]
  • rails 3.2.1

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

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

    最佳答案

    这是一个 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可以使用。

    关于ruby-on-rails - 为什么在 ActionView::OutputBuffer 上调用 URI.escape 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469825/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com