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 < 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/Nokogiri/XML/Node.html

Direct Known Subclasses

TargetScrubber

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePermitScrubber

Returns a new instance of PermitScrubber.



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

def initialize
  @direction = :bottom_up
  @tags, @attributes = nil, nil
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



48
49
50
# File 'lib/rails/html/scrubbers.rb', line 48

def attributes
  @attributes
end

#tagsObject

Returns the value of attribute tags.



48
49
50
# File 'lib/rails/html/scrubbers.rb', line 48

def tags
  @tags
end

Instance Method Details

#scrub(node) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rails/html/scrubbers.rb', line 63

def scrub(node)
  if node.cdata?
    text = node.document.create_text_node node.text
    node.replace text
    return CONTINUE
  end
  return CONTINUE if skip_node?(node)

  unless keep_node?(node)
    return STOP if scrub_node(node) == STOP
  end

  scrub_attributes(node)
end