mail_helper.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. module ActionMailer
  2. module MailHelper
  3. # Uses Text::Format to take the text and format it, indented two spaces for
  4. # each line, and wrapped at 72 columns.
  5. def block_format(text)
  6. formatted = text.split(/\n\r\n/).collect { |paragraph|
  7. format_paragraph(paragraph)
  8. }.join("\n")
  9. # Make list points stand on their own line
  10. formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
  11. formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
  12. formatted
  13. end
  14. # Access the mailer instance.
  15. def mailer
  16. @_controller
  17. end
  18. # Access the message instance.
  19. def message
  20. @_message
  21. end
  22. # Access the message attachments list.
  23. def attachments
  24. @_message.attachments
  25. end
  26. # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
  27. #
  28. # === Examples
  29. #
  30. # my_text = "Here is a sample text with more than 40 characters"
  31. #
  32. # format_paragraph(my_text, 25, 4)
  33. # # => " Here is a sample text with\n more than 40 characters"
  34. def format_paragraph(text, len = 72, indent = 2)
  35. sentences = [[]]
  36. text.split.each do |word|
  37. if (sentences.last + [word]).join(' ').length > len
  38. sentences << [word]
  39. else
  40. sentences.last << word
  41. end
  42. end
  43. sentences.map { |sentence|
  44. "#{" " * indent}#{sentence.join(' ')}"
  45. }.join "\n"
  46. end
  47. end
  48. end