Skip to content

Instantly share code, notes, and snippets.

@shivabhusal
Last active December 8, 2015 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivabhusal/2f17eecb3f4320193f12 to your computer and use it in GitHub Desktop.
Save shivabhusal/2f17eecb3f4320193f12 to your computer and use it in GitHub Desktop.
SendGrid integration; Transactional EMail template via Ruby : Send data to tr-email
# /email/base.rb
class Email::Base
# This class is mostly responsible for Sending email via SendGrid or Other Provier in future
# Code in here are Common to all its successors
RootURL = 'http://dashboard.thepact.com'
VarPrefix = '{{'
VarSuffix = '}}'
attr_reader :client, :from, :template, :subject, :recipients
def initialize(options)
@subject = ' '
@from = "noreply@jyaasa.com"
@client = SendGrid::Client.new do |c|
c.api_key = ENV['SENDGRID_API']
end
@recipients = parse_recipients(options[:to])
@template = SendGrid::Template.new(parse_template_id)
end
def send
mail_defaults = {
from: from,
html: html,
text: text,
subject: subject
}
mailer = SendGrid::TemplateMailer.new(client, template, recipients)
mailer.mail(mail_defaults)
end
protected
# Parses all the recipients from the Array
# @param tos [Array] collection of emails
# can of format [" Shiva Bhusal <shiva@jyaasa.com>", "info@jyaasa.com"]
# @return [Array] collection of SendGrid::Recipient
def parse_recipients(tos)
collection = []
tos = [tos].flatten
tos.map do |to|
recipient = SendGrid::Recipient.new(to)
add_contents(recipient)
collection << recipient
end
collection
end
# Adds contents in wrapped Data into SMTP Header
# to be sent to SendGrid / Email sender
# @param recipient [SendGrid::Recipient]
# @return [SendGrid::Recipient] Modified; substitution added
def add_contents(recipient)
wrapped_data.map do |key, value|
recipient.add_substitution(key, value)
end
recipient
end
# Wraps data with appropriate prefix and suffix
# @return [Hash] Modified value of Data hash
def wrapped_data
sample = data.merge(default_data)
result = sample.map do |key, value|
{(VarPrefix + key.to_s + VarSuffix) => value}
end
result.reduce(:merge)
end
# Data to be send to SendGrid to embed in template
# @note The data identifier shall have format
# %var_name%
# @note The Prefix and Suffix are auto added when SMTP request sent
# VarPrefix = 'sg_'
# VarSuffix = '_sg'
# @return [Hash]
# Example:
# {
# name: @pact.child.name
# }
#
def data
{
}
end
# HTML Contents to be substituted inplace of %body%
# @return [String]
# It can be String containing HTML Markups of any kind (Permitted only)
# @note it cannot be empty
#
def html
' '
end
# Text Contents to be substituted inplace of %body%
# @return [String]
# @note it cannot be empty
#
def text
' '
end
# The root URL relative to which assets URL to be fixed
# For example
# - if asset_url = '/images/facebook.png'
# then it has to be reference with resp to root_url
def root_url
RootURL
end
# Default data always to be passed to the transactional templates
# @note these data are subject to change so thay are extracted out here
#
# Like
# - title logo
# - social icons
# - email's assets URL
def default_data
{
'root_url' => RootURL,
'asset_url' => "#{RootURL}/sendgrid",
'signin_url' => "#{RootURL}/signin",
'signup_url' => "#{RootURL}/signup",
'dashboard_url' => "#{RootURL}/signin",
'faq_url' => "#{RootURL}/signin",
'resources_url' => "#{RootURL}/signin",
'help_desk_url' => "#{RootURL}/signin",
'src_facebook_icon' => "#{RootURL}/sendgrid/images/facebook_icon.png",
'src_twitter_icon' => "#{RootURL}/sendgrid/images/twitter_icon.png",
'src_pinterest_icon' => "#{RootURL}/sendgrid/images/pinterest_icon.png",
'src_logo_icon' => "#{RootURL}/sendgrid/images/logo.png",
'this_year' => Date.current.year.to_s,
'support_email' => "support@thepact.com",
'href_facebook' => "https://facebook.com/thepact",
'href_twitter' => "https://twitter.com/thepact",
'href_pinterest' => "https://pinterest.com/thepact",
}
end
def parse_template_id
conf = YAML.load(File.read Rails.root.join('config', 'email_templates.yml'))
this_class_name_with_namespaces = self.class.ancestors.first.to_s
conf[this_class_name_with_namespaces]
end
end
# in orders_signup/confirmation/pact_order.rb
class OrdersSignup::Confirmation::PactOrder < Email::Base
# Responsible solely for sending Pact Order Confirmation Email
# Send email with order information with login info / write to marketing email list
# @note @path is its property, it may not be present in its other siblings
#
attr_reader :pact
def initialize(options)
@pact = options[:pact]
super
end
def data
{
parent_first_name: subscriber.parent.first_name,
child_first_name: pact.child.first_name,
order_number: 123,
subscription_type: 'month',
billing_date: billing_date,
number_of_pacts_subscribed: subscriptions.count,
order_details_markup: order_details_markup,
parent_email: subscriber.email
}
end
private
def subscriptions
Stripe::Customer.retrieve(subscriber.stripe_id).subscriptions
end
def subscriber
pact.parent
end
def billing_date
Date.today.day.ordinalize
end
def order_details_markup
plans = ''
charge = 0
subscriptions.each do |subscription|
plans += <<-EOS
<li style="text-align: left">Plan Name: #{subscription.plan.name} : Plan amount USD $#{subscription.plan.amount/100.0}</li>
EOS
charge += subscription.plan.amount
end
total = "<p style=\"text-align: left\"><strong>Total Amount $#{charge/100.0}</strong></p>"
plans + total
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment