Class: Sanitize::Transformers::CSS::CleanElement

Inherits:
Object
  • Object
show all
Defined in:
lib/sanitize/transformers/clean_css.rb

Overview

Enforces a CSS allowlist on the contents of ‘<style>` elements.

Instance Method Summary collapse

Constructor Details

#initialize(sanitizer_or_config) ⇒ CleanElement

Returns a new instance of CleanElement.



32
33
34
35
36
37
38
# File 'lib/sanitize/transformers/clean_css.rb', line 32

def initialize(sanitizer_or_config)
  if Sanitize::CSS === sanitizer_or_config
    @scss = sanitizer_or_config
  else
    @scss = Sanitize::CSS.new(sanitizer_or_config)
  end
end

Instance Method Details

#call(env) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sanitize/transformers/clean_css.rb', line 40

def call(env)
  node = env[:node]

  return unless node.type == Nokogiri::XML::Node::ELEMENT_NODE &&
      env[:node_name] == 'style'

  css = @scss.stylesheet(node.content)

  if css.strip.empty?
    node.unlink
  else
    css.gsub!('</', '<\/')
    node.children.unlink
    node << Nokogiri::XML::Text.new(css, node.document)
  end
end