Jonny Peppers
Jonny Peppers

Reputation: 169

How to embed ruby in html inside ruby file?

I have a ruby file which I use to send email. I am using the code from a tutorial as follows:

 require 'net/smtp'
 test_arr = ["test", "test1"]

 message = <<MESSAGE_END
 From: Private Person <[email protected]>
 To: A Test User <[email protected]>
 MIME-Version: 1.0
 Content-type: text/html
 Subject: SMTP e-mail test

 This is an e-mail message to be sent in HTML format

 <b>This is HTML message.</b>
 <h1>This is headline.</h1>

 //Here I want to iterate through the Array test_arr and create a h1 element for each element in array

 <h1> test </h1>
 <h1> test1 </h1>
 MESSAGE_END

 Net::SMTP.start('localhost') do |smtp|
 smtp.send_message message, '[email protected]', 
                         '[email protected]'
 end

I have tried <% to inject ruby code to iterate the array but does not seem to work. How could I iterate through the test_arr Array inside that HTML message?

Upvotes: 0

Views: 2898

Answers (3)

sawa
sawa

Reputation: 168081

Put a line:

test_arr.map{|e| "<h1>#{e}</h1>"}.join($/)

in the relevant position.

Alternatively, you can use my dom gem:

require "dom"

message = [
  <<~MESSAGE_END,
    From: Private Person <[email protected]>
    To: A Test User <[email protected]>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: SMTP e-mail test

    This is an e-mail message to be sent in HTML format
  MESSAGE_END
  "This is HTML message.".dom(:b),
  "This is headline.".dom(:h1),
  test_arr.dom(:h1, nil),
].dom

Upvotes: 0

Doon
Doon

Reputation: 20232

You will need to use something like erb to create it as template.

Something like this should work.

require 'net/smtp'
require 'erb' 

 test_arr = ["test", "test1"]

 message = <<MESSAGE_END
 From: Private Person <[email protected]>
 To: A Test User <[email protected]>
 MIME-Version: 1.0
 Content-type: text/html
 Subject: SMTP e-mail test

 This is an e-mail message to be sent in HTML format

 <b>This is HTML message.</b>
 <h1>This is headline.</h1>

 <% test_arr.each() do |ta| %>
    <h1><%=ta%></h1>  
 <% end %>

 MESSAGE_END
 # create a renderer to parse our template 
 renderer = ERB.new(message)
 Net::SMTP.start('localhost') do |smtp|
 smtp.send_message renderer.result(), '[email protected]', 
                         '[email protected]'

 end

notice that you need to require 'erb' in your script, create the template, in this case a simple block to iterate over the array. You then need to create a renderer from the template with Erb.new(template_name). Once you have the renderer, you need to call #result on it to get the rendered output. You can look at the erb documentation for more information (http://ruby-doc.org/stdlib-2.3.1/libdoc/erb/rdoc/ERB.html)

Upvotes: 0

PS.
PS.

Reputation: 343

Save the file as .html.erb to use embedded ruby codes with <%= ruby_code %> in html message.

Upvotes: 1

Related Questions