plain_text_formatter.rb 655 B

12345678910111213141516171819202122232425262728293031
  1. # frozen_string_literal: true
  2. class PlainTextFormatter
  3. NEWLINE_TAGS_RE = %r{(<br />|<br>|</p>)+}
  4. attr_reader :text, :local
  5. alias local? local
  6. def initialize(text, local)
  7. @text = text
  8. @local = local
  9. end
  10. def to_s
  11. if local?
  12. text
  13. else
  14. node = Nokogiri::HTML.fragment(insert_newlines)
  15. # Elements that are entirely removed with our Sanitize config
  16. node.xpath('.//iframe|.//math|.//noembed|.//noframes|.//noscript|.//plaintext|.//script|.//style|.//svg|.//xmp').remove
  17. node.text.chomp
  18. end
  19. end
  20. private
  21. def insert_newlines
  22. text.gsub(NEWLINE_TAGS_RE) { |match| "#{match}\n" }
  23. end
  24. end