Skip to content

Instantly share code, notes, and snippets.

@rennex
Created August 11, 2013 03:44
Show Gist options
  • Save rennex/6203288 to your computer and use it in GitHub Desktop.
Save rennex/6203288 to your computer and use it in GitHub Desktop.
Email template system for constructing plaintext emails (the example shows usage in a Sinatra route, with the mail gem)
class EmailTemplate
def initialize
@io = StringIO.new
end
def puts(*args)
@io.puts *args
end
def print(*args)
@io.print *args
end
def render(*args, &block)
# this loop is to catch next/break from the block, iirc
1.times do
# this lets us override puts and print in the block
instance_exec *args, &block
end
@io.string.gsub(/\r/, "")
end
def self.render(*args, &block)
EmailTemplate.new.render *args, &block
end
end
# this gets eval()'d in the context of the Sinatra route, so instance vars (@u) work
# (but it must be passed as an argument to the template block)
EmailTemplate.render(@u) do |u|
if u.balance >= 0
puts "(no debt)"
next
end
puts <<EOF
Howdy! blah blah..
Multiple lines too.
EOF
if u.stuff?
puts "Also, stuff."
end
puts "\n\n"
end
post "/email" do
m = Mail.new do
from "me@here.com"
subject "Whatever"
to @u.email
end
m.body = eval(File.read("samplemail.rb"), binding, "samplemail.rb")
m.charset = "UTF-8"
m.deliver
haml "%h2 Message sent!\n%p To: #{m.to}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment