获取Rails 3默认清理输出而不是转义它

时间:2012-01-01 03:34:41

标签: ruby-on-rails escaping xss

默认情况下,Rails 3会转义您直接输出的字符串 - 例如,<%= '<h1>' %>呈现为&lt;h1&gt;

因此,我不得不烦恼地做这件事:

<%= sanitize @post.body %>

有什么方法可以将它作为默认值吗?即,我想要这个:

<%= @post.body %>

相当于:

<%= sanitize @post.body %>

而不是:

<%= h @post.body %>

默认为

2 个答案:

答案 0 :(得分:2)

class ActiveSupport::SafeBuffer
  def concat(value)
    super(ERB::Util.h(value))
  end
  alias << concat
  def dirty?
    false
  end
end

享受XSS的乐趣。不要在生产中使用。这确实完全禁用了XSS保护,你甚至无法明确地告诉一段数据是不安全的。我宁愿做

class Post
  def body_with_raw
    body_without_raw.html_safe
  end
  alias_method_chain :body, :raw
end

甚至

class ActiveRecord::Base
  def self.html_safe(*attributes)
    attributes.each do |attribute|
      name = attribute + "with_raw"
      before = attribute + "without_raw"
      define_method name do
        before.html_safe
      end
      alias_method_chain attribute, "raw"
    end
  end
end

所以你可以

class Post
  html_safe :body
end

答案 1 :(得分:1)

根据塔斯的回答,我觉得这可能有用(但我不确定):

class ActiveSupport::SafeBuffer
  def concat(value)
    if dirty? || value.html_safe?
      super(value)
    else
      # super(ERB::Util.h(value)) # this is what Rails does by default
      super(ActionController::Base.helpers.sanitize(value))
    end
  end
end