33

I'm trying to call sanitize within a controller. Here's what I tried:

class FooController < ApplicationController
  include ActionView::Helpers::SanitizeHelper
  # ...
end

However, I'm getting this error:

undefined method `white_list_sanitizer' for FooController:Class

I searched around and people recommended switching the include line to include ActionView::Helpers, but that results in this error:

undefined method `url_for' for nil:NilClass

What's the correct way to call sanitize? I'm using Rails 2.3.5.

pmc255
  • 1,499
  • 2
  • 19
  • 31
  • 1
    To, for example, sanitize user input before passing it to RDiscount to generate HTML from Markdown content. – pmc255 Oct 21 '10 at 10:32

3 Answers3

58

you can use this ActionController::Base.helpers inside action method:

class SiteController < ApplicationController
  def index
    render :text => ActionController::Base.helpers.sanitize('<b>bold</b>')
  end
end

Hope this helps

JCorcuera
  • 6,794
  • 2
  • 35
  • 29
  • Thanks a lot! Just for the record (and google): this is the perfect solution to use sanitizer from a helper method that's called from a controller. – Laszlo T Jan 01 '14 at 15:24
  • 3
    Great answer, still. Can also abbreviate to just `helpers.sanitize('bold')` for brevity. – SRack Nov 02 '20 at 14:31
5

Rails 6:

To strip links (for example) from a text, just call:

...
Rails::Html::LinkSanitizer.new.sanitize("links here will be stripped")
...

see https://github.com/rails/rails-html-sanitizer

Arta
  • 5,127
  • 5
  • 25
  • 23
-2

I'm not sure what you're trying to do here but I'm almost 100% certain it doesn't belong in the controller.

If you want to sanitize an attribute before you save it to the DB, do so in the model with a before save callback.

Otherwise, sanitize in the view template or view helper.

bodacious
  • 6,608
  • 9
  • 45
  • 74