Class: Rails::HTML::PermitScrubber

Inherits:
Loofah::Scrubber
  • Object
show all
Defined in:
lib/rails/html/scrubbers.rb

Overview

Rails::HTML::PermitScrubber

Rails::HTML::PermitScrubber allows you to permit only your own tags and/or attributes.

Rails::HTML::PermitScrubber can be subclassed to determine:

  • When a node should be skipped via skip_node?.

  • When a node is allowed via allowed_node?.

  • When an attribute should be scrubbed via scrub_attribute?.

Subclasses don’t need to worry if tags or attributes are set or not. If tags or attributes are not set, Loofah’s behavior will be used. If you override allowed_node? and no tags are set, it will not be called. Instead Loofahs behavior will be used. Likewise for scrub_attribute? and attributes respectively.

Text and CDATA nodes are skipped by default. Unallowed elements will be stripped, i.e. element is removed but its subtree kept. Supplied tags and attributes should be Enumerables.

tags= If set, elements excluded will be stripped. If not, elements are stripped based on Loofahs HTML5::Scrub.allowed_element?.

attributes= If set, attributes excluded will be removed. If not, attributes are removed based on Loofahs HTML5::Scrub.scrub_attributes.

class CommentScrubber < Rails::HTML::PermitScrubber
  def initialize
    super
    self.tags = %w(form script comment blockquote)
  end

  def skip_node?(node)
    node.text?
  end

  def scrub_attribute?(name)
    name == "style"
  end
end

See the documentation for Nokogiri::XML::Node to understand what’s possible with nodes: nokogiri.org/rdoc/Nokogiri/XML/Node.html

Direct Known Subclasses

TargetScrubber

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prune: false) ⇒ PermitScrubber

Returns a new instance of PermitScrubber.



52
53
54
55
56
# File 'lib/rails/html/scrubbers.rb', line 52

def initialize(prune: false)
  @prune = prune
  @direction = @prune ? :top_down : :bottom_up
  @tags, @attributes = nil, nil
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



50
51
52
# File 'lib/rails/html/scrubbers.rb', line 50

def attributes
  @attributes
end

#pruneObject (readonly)

Returns the value of attribute prune.



50
51
52
# File 'lib/rails/html/scrubbers.rb', line 50

def prune
  @prune
end

#tagsObject

Returns the value of attribute tags.



50
51
52
# File 'lib/rails/html/scrubbers.rb', line 50

def tags
  @tags
end

Instance Method Details

#scrub(node) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rails/html/scrubbers.rb', line 66

def scrub(node)
  if Loofah::HTML5::Scrub.cdata_needs_escaping?(node)
    replacement = Loofah::HTML5::Scrub.cdata_escape(node)
    node.replace(replacement)
    return CONTINUE
  end
  return CONTINUE if skip_node?(node)

  unless (node.element? || node.comment?) && keep_node?(node)
    return STOP if scrub_node(node) == STOP
  end

  scrub_attributes(node)
end