rails_has_elegance
rails_has_elegance

Reputation: 1692

Rails 3 - Alternative to html_safe on user generated comment content?

A html_safe method on user generated comment content really is not a good solution, obviously. However, this was, so far, the only solution I could come up with to implement the following feature: I wanted to enable users to quote another comment simply by typing the iteration id of the other comment into the comment form like this "#14" (to quote comment 14 of that article). Then this #14 gets replaced with "[quoted_comment.content]" in the content output.

This is my code for it in the comment model:

def content_with_quotes
  if content.match(/(#([0-9]+))\s/)
    comment_content = content
    comment_content.scan(/(#([0-9]+))\s/) do
      if quoted_comment = Comment.where(article_id: self.article_id).where(iteration_id: $2).first
        if quoted_comment.created_at < self.created_at
          return comment_content.sub(/(#[0-9]+)\s/, "<i>'#{quoted_comment.content}'</i> ")
        end
      end
    end
  else
    return content
  end
end

Then in my comment view, I apply it with comment.content_with_quotes.html_safe and everything works fine.

So, this is what I want, and it works, but of course this html_safe method is a bad idea for user submitted content, since it might not be html safe.
Any suggestions on how to approach my feature without doing the html_safe method?

Upvotes: 0

Views: 2832

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32748

I'd consider using a white-list approach and use the HTML Sanitizer methods to clean your strings.

See http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

Upvotes: 3

Related Questions