plain_text_formatter.rb 475 B

123456789101112131415161718192021222324252627282930
  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. 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. end