Marc-André Lafortune
Marc-André Lafortune

Reputation: 79552

Mark ActiveRecord attribute as html_safe

We have an ActiveRecord model with an html attribute (say Post#body). Is there a nice way that calling body on a post returns an html_safe? string? E.g.:

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

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

The problem otherwise is that we have to call raw everything we show that field.

Upvotes: 2

Views: 956

Answers (2)

bpaul
bpaul

Reputation: 1949

FYI. I made a module for this

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

to use it just include it in your model and add the attributes you want to avoid using raw for to a sanitize_on_input_only line like the following:

sanitize_on_input_only :message, :another_attribute, ...

Upvotes: 0

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79552

Here's a way I found:

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

Upvotes: 3

Related Questions