1

我编写了一个 ruby​​ 脚本,通过读取文件的内容使用 smtp 发送邮件。一个文件的内容是:

+3456|0|2013-04-16|2013-04-19
+3456|0|2013-04-16|2013-05-19

我发送邮件的代码如下:

content = File.read(file_name)   
message = << MESSAGE_END   
From: from@localdomain.com
To: to@localdomain.com
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP e-mail test
Body
**HTML CODE to display the table with rows equal to the number of records in the file**
MESSAGE_END

Net::SMTP.start('localhost') do |smtp| 
  smtp.send_message message, 'from@localdomain.com','to@localdomain.com'
end

现在我的问题是如何编写一个 html 代码来创建一个表,其行和列等于文件中的记录数(因为文件中的记录会相应变化)?文件中的记录总是'|' 分开。

4

2 回答 2

1

您可以使用content_tag助手和String#split。例如:

def row_markup(row)
  content_tag(:tr) do
    row.map{ |elem| content_tag(:td, elem) }.reduce(:+)
  end
end

def table_markup(rows)
  content_tag(:table) do
    rows.map{ |row| row_markup(row.split("|")) }.reduce(:+)
  end
end

然后打电话

table_markup(read_data_from_file.split("\n"))
于 2013-04-23T07:17:57.917 回答
0

假设您的输入文件位于./input.txt,那么您可以执行以下操作:

require 'builder'

html = Builder::XmlMarkup.new
html.table do
  File.open('./input.txt', 'r').each_line do |line|
   html.tr do
      line.chomp.split('|').each do |column|
        html.td column
      end
    end
  end
end

message << html.to_html
于 2013-04-23T07:27:37.093 回答