In Rails 4.2 and above this gem will be responsible for sanitizing HTML fragments in Rails applications, i.e. in the
Rails Html Sanitizer is only intended to be used with Rails applications. If you need similar functionality in non Rails apps consider using Loofah directly (that's what handles sanitization under the hood).
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install rails-html-sanitizer
All sanitizers respond to
full_sanitizer = Rails::Html::FullSanitizer.new full_sanitizer.sanitize("Bold no more! See more here...") # => Bold no more! See more here...
link_sanitizer = Rails::Html::LinkSanitizer.new link_sanitizer.sanitize('Only the link text will be kept.') # => Only the link text will be kept.
safe_list_sanitizer = Rails::Html::SafeListSanitizer.new
sanitize via an extensive safe list of allowed elements
safe list only the supplied tags and attributes
safe_list_sanitizer.sanitize(@article.body, tags: %w(table tr td), attributes: %w(id class style))
safe list via a custom scrubber
safe_list_sanitizer.sanitize(@article.body, scrubber: ArticleScrubber.new)
safe list sanitizer can also sanitize css
Scrubbers are objects responsible for removing nodes or attributes you don't want in your HTML document.
This gem includes two scrubbers
This scrubber allows you to permit only the tags and attributes you want.
scrubber = Rails::Html::PermitScrubber.new scrubber.tags = ['a']
PermitScrubberpicks out tags and attributes to permit in sanitization,
Rails::Html::TargetScrubbertargets them for removal.
scrubber = Rails::Html::TargetScrubber.new scrubber.tags = ['img']
You can also create custom scrubbers in your application if you want to.
class CommentScrubber < Rails::Html::PermitScrubber def initialize super self.tags = %w( form script comment blockquote ) self.attributes = %w( style ) end
def skip_node?(node) node.text? end end
Rails::Html::PermitScrubberdocumentation to learn more about which methods can be overridden.
CommentScrubberfrom above, you can use this in a Rails view like so:
Loofah is what underlies the sanitizers and scrubbers of rails-html-sanitizer. - Loofah and Loofah Scrubbers
nodeargument passed to some methods in a custom scrubber is an instance of
Rails Html Sanitizers is work of many contributors. You're encouraged to submit pull requests, propose features and discuss issues.
Rails Html Sanitizers is released under the MIT License.