Created
August 11, 2013 03:44
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
post "/email" do | |
m = Mail.new do | |
from "[email protected]" | |
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