将ActiveRecord属性标记为html_safe

时间:2012-05-02 19:19:27

标签: ruby-on-rails activerecord html-safe

我们有一个带有html属性的ActiveRecord模型(比如Post#body)。有一种很好的方法,在body上调用post会返回一个html_safe?字符串吗? E.g:

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

FYI。我为此制作了一个模块

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的属性添加到sanitize_on_input_only行,如下所示:

sanitize_on_input_only :message, :another_attribute, ...