Skip to content

Instantly share code, notes, and snippets.

@mupkoo
Created February 5, 2018 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mupkoo/58ef3ced0a03b2792f359ac74828da60 to your computer and use it in GitHub Desktop.
Save mupkoo/58ef3ced0a03b2792f359ac74828da60 to your computer and use it in GitHub Desktop.
Simple content configuration for sanitize gem
# frozen_string_literal: true
require 'uri'
ALLOWED_IFRAME_TLDS = %w[
facebook.com
google.com
twitter.com
vimeo.com
youtube.com
].freeze
allowed_iframes = lambda do |env|
node = env[:node]
node_name = env[:node_name]
return if env[:is_whitelisted] || !node.element?
return unless node_name == 'iframe'
src_tld =
if node['src'].present? && node['src'] =~ URI.regexp(%w[http https])
URI(node['src'].to_s).host.split('.').last(2).join('.')
end
return unless ALLOWED_IFRAME_TLDS.include?(src_tld)
Sanitize.clean_node!(node,
elements: %w[iframe],
attributes: {
'iframe' => %w[allowfullscreen webkitallowfullscreen mozallowfullscreen frameborder height src width]
}
)
{ node_whitelist: [node] }
end
remove_empty_tags = lambda do |env|
node = env[:node]
node_name = env[:node_name]
return if %w[td img br hr iframe].include? node_name
return unless node.elem?
unless node.children.any? { |c| !c.text? || !c.content.strip.empty? }
node.unlink
end
end
Sanitize::Config::CONTENT = {
elements: %w[
a b blockquote br col colgroup
del em h1 h2 h3 h4 h5 h6 hgroup hr i img
li ol p pre small strike strong
table tbody td tfoot th thead time tr u ul
],
attributes: {
:all => %w[dir lang title],
'a' => %w[href],
'blockquote' => %w[cite],
'del' => %w[cite datetime],
'img' => %w[align alt height src width],
'table' => %w[summary width],
'td' => %w[abbr axis colspan rowspan width],
'th' => %w[abbr axis colspan rowspan scope width],
'time' => %w[datetime pubdate]
},
add_attributes: {
'a' => { 'rel' => 'nofollow', 'target' => '_blank' },
'table' => { 'class' => 'table' },
'img' => { 'class' => 'img-fluid' }
},
protocols: {
'a' => { 'href' => ['ftp', 'http', 'https', 'mailto', :relative] },
'blockquote' => { 'cite' => ['http', 'https', :relative] },
'del' => { 'cite' => ['http', 'https', :relative] },
'img' => { 'src' => ['http', 'https', :relative] }
},
transformers: [
allowed_iframes,
remove_empty_tags
]
}.freeze
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment