Skip to content

Commit

Permalink
Merge 7da407e into 1b9e634
Browse files Browse the repository at this point in the history
  • Loading branch information
difernandez committed Jun 3, 2019
2 parents 1b9e634 + 7da407e commit b349237
Show file tree
Hide file tree
Showing 8 changed files with 588 additions and 399 deletions.
17 changes: 11 additions & 6 deletions lib/send_grid_mailer/api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,32 @@ module SendGridMailer
class Api
include Logger

SUCCESS_CODE = 202
SUCCESS_CODES = { mail: 202, template: 200 }

def initialize(api_key)
@api_key = api_key || raise(SendGridMailer::InvalidApiKey)
end

def send_mail(sg_definition)
response = sg_api.client.mail._('send').post(request_body: sg_definition.to_json)
handle_response(response)
handle_response(response, :mail)
end

def get_template(sg_definition)
response = sg_api.client.templates._(sg_definition.mail.template_id).get()
handle_response(response, :template)
end

private

def handle_response(response)
if response.status_code.to_i != SUCCESS_CODE
def handle_response(response, api_call_type)
if response.status_code.to_i != SUCCESS_CODES[api_call_type]
errors = response_errors(response)
log_api_error_response(response.status_code, errors)
log_api_error_response(response.status_code, errors, api_call_type)
raise SendGridMailer::ApiError.new(response.status_code, errors)
end

log_api_success_response(response)
log_api_success_response(response, api_call_type)
response
end

Expand Down
60 changes: 60 additions & 0 deletions lib/send_grid_mailer/dev_deliverer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
module SendGridMailer
class DevDeliverer
include InterceptorsHandler
include Logger
require "letter_opener"

def deliver!(sg_definition)
@sg_definition = sg_definition
execute_interceptors(@sg_definition)
log_definition(@sg_definition)
letter_opener_delivery_method.deliver!(mail)
end

private

def sg_api
@sg_api ||= Api.new(api_key)
end

def api_key
Rails.application.config.action_mailer.sendgrid_dev_settings[:api_key]
rescue
nil
end

def letter_opener_delivery_method
@letter_opener_delivery_method ||= LetterOpener::DeliveryMethod.new(location: '/tmp/mails')
end

def parsed_template
template_response = sg_api.get_template(@sg_definition)
template_active_version = JSON.parse(template_response.body)["versions"].find do |version|
version["active"] == 1
end
template_content = template_active_version["html_content"]
@sg_definition.personalization.substitutions.each { |k, v| template_content.gsub!(k, v) }
template_content
end

def emails(origin)
@emails ||= {}
return @emails[origin] if @emails.has_key?(origin)

@emails[origin] = @sg_definition.personalization.send(origin)&.map {|em| em["email"]}
end

def mail
template = parsed_template.html_safe
m = Mail.new
m.html_part = template
m.subject = @sg_definition.personalization.subject
m.from = @sg_definition.mail.from["email"] if @sg_definition.mail.from.present?
m.to = emails(:tos) if emails(:tos).present?
m.cc = emails(:ccs) if emails(:ccs).present?
m.bcc = emails(:bccs) if emails(:bccs).present?

m
end
end
end
4 changes: 3 additions & 1 deletion lib/send_grid_mailer/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ class Engine < ::Rails::Engine
require_relative "./mailer_base_ext"
end

initializer "add_sendgrid_deliverer", before: "action_mailer.set_configs" do
initializer "add_sendgrid_deliverers", before: "action_mailer.set_configs" do
require_relative "./dev_deliverer"
require_relative "./deliverer"
ActionMailer::Base.add_delivery_method(:sendgrid, SendGridMailer::Deliverer)
ActionMailer::Base.add_delivery_method(:sendgrid_dev, SendGridMailer::DevDeliverer)
end
end
end
26 changes: 22 additions & 4 deletions lib/send_grid_mailer/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,36 @@ def log_definition(definition)
log(build_definition_message(data))
end

def log_api_success_response(response)
log("The E-mail was successfully sent :)\nStatus Code: #{response.status_code}")
def log_api_success_response(response, api_call_type)
log(success_message(response, api_call_type))
end

def log_api_error_response(status_code, errors)
msg = "The E-mail was not sent :(\nStatus Code: #{status_code}\nErrors:"
def log_api_error_response(status_code, errors, api_call_type)
msg = failure_message(status_code, api_call_type)
msg += log_errors(errors)
log(msg)
end

private

def success_message(response, api_call_type)
case api_call_type
when :mail
"The E-mail was successfully sent :)\nStatus Code: #{response.status_code}"
when :template
"The template was succesfully fetched :)\nStatus Code: #{response.status_code}"
end
end

def failure_message(status_code, api_call_type)
case api_call_type
when :mail
"The E-mail was not sent :(\nStatus Code: #{status_code}\nErrors:"
when :template
"The template was not fetched :(\nStatus Code: #{status_code}\nErrors:"
end
end

def log(msg)
Rails.logger.info("\n#{msg}")
nil
Expand Down
12 changes: 10 additions & 2 deletions lib/send_grid_mailer/mailer_base_ext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def mail(headers = {}, &_block)

define_sg_mail(headers)

SendGridMailer::Deliverer.new.deliver!(sg_definition)
deliverer&.new&.deliver!(sg_definition)
end

private
Expand Down Expand Up @@ -82,8 +82,16 @@ def sg_definition
@sg_definition ||= SendGridMailer::Definition.new
end

def deliverer
if self.class.delivery_method == :sendgrid_dev
SendGridMailer::DevDeliverer
elsif self.class.delivery_method == :sendgrid
SendGridMailer::Deliverer
end
end

def enabled_sendgrid?
self.class.delivery_method == :sendgrid
[:sendgrid, :sendgrid_dev].include?(self.class.delivery_method)
end
end
end
3 changes: 2 additions & 1 deletion send_grid_mailer.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ Gem::Specification.new do |s|

s.add_dependency "rails", ">= 4.2.0"
s.add_dependency "sendgrid-ruby", "~> 4.0", ">= 4.0.4"
s.add_dependency "letter_opener", "~> 1.7.0"
s.add_development_dependency "pry"
s.add_development_dependency "pry-rails"
s.add_development_dependency "sqlite3"
s.add_development_dependency "sqlite3", "~> 1.3.13"
s.add_development_dependency "rspec-rails", "~> 3.4.0"
s.add_development_dependency "guard-rspec", "~> 4.7"
s.add_development_dependency "factory_bot_rails"
Expand Down
6 changes: 6 additions & 0 deletions spec/dummy/app/mailers/test_mailer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,10 @@ def substitutions_email
substitute "%key2%", "value2"
mail(body: "X")
end

def template_with_substitutions_email(value)
set_template_id("XXX")
substitute "%key%", value
mail(to: "r1@platan.us", body: "X")
end
end

0 comments on commit b349237

Please sign in to comment.