跳至內容 跳至搜尋

Action Mailer MailHelper

提供 ActionMailer::Base 的輔助器方法,可用於輕鬆格式化訊息、存取郵件傳送器或訊息實例,以及附件清單。

方法
A
B
F
M

實例公用方法

attachments()

存取訊息附件清單。

# File actionmailer/lib/action_mailer/mail_helper.rb, line 53
def attachments
  mailer.attachments
end

block_format(text)

擷取文字,並將其格式化,每一行縮排兩個空格,並換行為 72 行

text = <<-TEXT
  This is
  the      paragraph.

  * item1 * item2
TEXT

block_format text
# => "  This is the paragraph.\n\n  * item1\n  * item2\n"
# File actionmailer/lib/action_mailer/mail_helper.rb, line 22
def block_format(text)
  formatted = text.split(/\n\r?\n/).collect { |paragraph|
    format_paragraph(paragraph)
  }.join("\n\n")

  # Make list points stand on their own line
  output = +""
  splits = formatted.split(/(\*+|\#+)/)
  while line = splits.shift
    if line.start_with?("*", "#") && splits.first&.start_with?(" ")
      output.chomp!(" ") while output.end_with?(" ")
      output << "  #{line} #{splits.shift.strip}\n"
    else
      output << line
    end
  end

  output
end

format_paragraph(text, len = 72, indent = 2)

傳回 text,換行長度為 len 行,並縮排 indent 個空格。預設換行長度 len 等於 72 個字元,縮排 indent 等於兩個空格。

my_text = 'Here is a sample text with more than 40 characters'

format_paragraph(my_text, 25, 4)
# => "    Here is a sample text with\n    more than 40 characters"
# File actionmailer/lib/action_mailer/mail_helper.rb, line 65
def format_paragraph(text, len = 72, indent = 2)
  sentences = [[]]

  text.split.each do |word|
    if sentences.first.present? && (sentences.last + [word]).join(" ").length > len
      sentences << [word]
    else
      sentences.last << word
    end
  end

  indentation = " " * indent
  sentences.map! { |sentence|
    "#{indentation}#{sentence.join(' ')}"
  }.join "\n"
end

mailer()

存取郵件傳送器實例。

# File actionmailer/lib/action_mailer/mail_helper.rb, line 43
def mailer
  @_controller
end

message()

存取訊息實例。

# File actionmailer/lib/action_mailer/mail_helper.rb, line 48
def message
  @_message
end