Topic: How to override h() (html_escape)?

I want to allow my users to enter some html, such as <br />. Agile Web Dev With Rails seems to recommend against using sanitize(). Is there a way I can override h(), or somehow control exactly what h() or sanitize() do allow?

Re: How to override h() (html_escape)?

What tags do you wish to strip out/allow? If you just want to get rid of links there's strip_links(), but if you want to get more sophisticated in what you allow or disallow you'll probably have to write your own method.

vinnie - rails forum admin

Re: How to override h() (html_escape)?

Thanks, but strip_links won't do it. By default, I want to strip everything (javascript especially, but anything else that could be dangerous). I'd like the ability to then go back and add only what I deem to be safe and absolutely necessary for my app, such as <br />. This has to be a common problem.

A hackaround would be to run the text through h() and then add back any tags I don't mind passing on to the browser. There has to be a better way though- ideally a config file of allowed tags?

Re: How to override h() (html_escape)?

Well, the 'h' method is actually dead simple.  Here's the whole thing (the source can be found at http://www.ruby-doc.org/stdlib/libdoc/e … l#M000376)

class ERB
  module Utils
    def html_escape(s)
      s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
    end
    alias_method :h, :html_escape
  end
end

The way to override this is simple to include the above snippet of code somewhere in your application (probably environment.rb or, more cleanly, in  it's own file in the ./lib/ folder) and modify it how you want.

Good luck!

Re: How to override h() (html_escape)?

Awesome, thanks Danger! I looked for that but I'm still learning where in all my bookmarks to find such things.