jam-cloud/ruby/lib/jam_ruby/lib/html_sanitize.rb

56 lines
1.1 KiB
Ruby

require 'sanitize'
module JamRuby
module HtmlSanitize
SAFE = ['a', 'strong', 'em', 'i', 'ul', 'ol', 'li', 'p', 'b']
extend ActiveSupport::Concern
included do
class_attribute :html_sanitize_options
self.sanitize
end
def sanitize_fields
return if self.html_sanitize_options.nil?
# strict means use Sanitize's strictest settings, which removes all tags
strict_fields = html_sanitize_options[:strict] || []
strict_fields.each do |field|
value = self[field]
next if value.nil? || !value.is_a?(String)
self[field] = Sanitize.fragment(value)
end
# safe means to allow formatting tags only
safe_fields = html_sanitize_options[:safe] || []
safe_fields.each do |field|
value = self[field]
next if value.nil? || !value.is_a?(String)
self[field] = Sanitize.fragment(value, elements: SAFE)
end
end
module ClassMethods
def html_sanitize(options = {strict: []})
self.html_sanitize_options = options
end
def sanitize (options = {})
before_validation :sanitize_fields
end
end
end
end