Class: Govspeak::HtmlSanitizer

Inherits:
Object
  • Object
show all
Includes:
WithDeepMerge
Defined in:
lib/govspeak/html_sanitizer.rb

Defined Under Namespace

Classes: ImageSourceWhitelister, TableCellTextAlignWhitelister

Instance Method Summary collapse

Methods included from WithDeepMerge

#deep_merge

Constructor Details

#initialize(dirty_html, options = {}) ⇒ HtmlSanitizer

Returns a new instance of HtmlSanitizer.



41
42
43
44
# File 'lib/govspeak/html_sanitizer.rb', line 41

def initialize(dirty_html, options = {})
  @dirty_html = dirty_html
  @allowed_image_hosts = options[:allowed_image_hosts]
end

Instance Method Details

#button_sanitize_configObject



60
61
62
63
64
65
66
# File 'lib/govspeak/html_sanitizer.rb', line 60

def button_sanitize_config
  [
    "data-module='cross-domain-tracking'",
    "data-tracking-code",
    "data-tracking-name"
  ]
end

#sanitizeObject



46
47
48
49
50
51
52
# File 'lib/govspeak/html_sanitizer.rb', line 46

def sanitize
  transformers = [TableCellTextAlignWhitelister.new]
  if @allowed_image_hosts && @allowed_image_hosts.any?
    transformers << ImageSourceWhitelister.new(@allowed_image_hosts)
  end
  Sanitize.clean(@dirty_html, sanitize_config.merge(transformers: transformers))
end

#sanitize_configObject



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/govspeak/html_sanitizer.rb', line 68

def sanitize_config
  deep_merge(Sanitize::Config::RELAXED, {
    attributes: {
      :all => Sanitize::Config::RELAXED[:attributes][:all] + [ "id", "class", "role", "aria-label" ],
      "a"  => Sanitize::Config::RELAXED[:attributes]["a"] + ["rel"] + button_sanitize_config,
      "th"  => Sanitize::Config::RELAXED[:attributes]["th"] + [ "style" ],
      "td"  => Sanitize::Config::RELAXED[:attributes]["td"] + [ "style" ],
    },
    elements: Sanitize::Config::RELAXED[:elements] + [ "div", "span", "aside" ],
  })
end

#sanitize_without_imagesObject



54
55
56
57
58
# File 'lib/govspeak/html_sanitizer.rb', line 54

def sanitize_without_images
  config = sanitize_config
  config[:elements].delete('img')
  Sanitize.clean(@dirty_html, config)
end