2

我们有一个带有 html 属性的 ActiveRecord 模型(比如Post#body)。有没有一种调用bodyapost返回html_safe?字符串的好方法?例如:

class Post < ActiveRecord::Base
  # is_html_escaped :body or somesuch magic
end

Post.first.body.html_safe? # => true

否则问题是我们必须调用raw我们显示该字段的所有内容。

4

2 回答 2

3

这是我找到的一种方法:

class Post < ActiveRecord::Base
  def message
    super.html_safe
  end

  def message=(new_mess)
    new_mess = ERB::Util.html_escape(new_mess.sanitize) unless new_mess.html_safe?
    super(new_mess)
  end
end
于 2012-05-02T19:53:57.113 回答
0

供参考。我为此做了一个模块

module SanitizeOnly

  def self.included(mod)
    mod.extend(ClassMethods)
  end

  module ClassMethods

    def sanitize_on_input_only(*attribute_names)

      attribute_names.map(&:to_s).each do | attribute_name |
        class_eval <<-RUBY, __FILE__, __LINE__ + 1

        def #{attribute_name}
          super.html_safe
        end

        def #{attribute_name}=(new_val)
          new_val = ERB::Util.html_escape(new_val.sanitize) unless new_val.html_safe?
          super(new_val)
        end

      RUBY
      end
    end

  end
end

要使用它,只需将其包含在模型中,并将要避免使用 raw for 的属性添加到 sanitize_on_input_only 行,如下所示:

sanitize_on_input_only :message, :another_attribute, ...
于 2015-01-31T00:51:46.693 回答