plain_text_formatter.rb 545 B

12345678910111213141516171819202122232425262728293031323334
  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