You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
545 B

  1. # frozen_string_literal: true
  2. class PlainTextFormatter
  3. include ActionView::Helpers::TextHelper
  4. NEWLINE_TAGS_RE = /(<br \/>|<br>|<\/p>)+/.freeze
  5. attr_reader :text, :local
  6. alias local? local
  7. def initialize(text, local)
  8. @text = text
  9. @local = local
  10. end
  11. def to_s
  12. if local?
  13. text
  14. else
  15. html_entities.decode(strip_tags(insert_newlines)).chomp
  16. end
  17. end
  18. private
  19. def insert_newlines
  20. text.gsub(NEWLINE_TAGS_RE) { |match| "#{match}\n" }
  21. end
  22. def html_entities
  23. HTMLEntities.new
  24. end
  25. end