Setting SendGrid category to ActionMailer mailer and action in Rails 3.
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
# By Joakim Kolsjö and Henrik Nyh of Barsoom AB. MIT license. | |
class ApplicationMailer < ActionMailer::Base | |
def custom_mail(options) | |
text = options.delete(:text) | |
add_sendgrid_headers | |
mail(options) do |format| | |
format.text { render(text: text) } | |
end | |
end | |
# Set headers for SendGrid statistics: http://sendgrid.com/ | |
def add_sendgrid_headers | |
mailer, action = calling_mailer_and_action | |
headers "X-SMTPAPI" => "{ \"category\": \"#{mailer}##{action}\" }" | |
end | |
# Returns e.g. [ "FooMailer", "my_action" ] | |
def calling_mailer_and_action | |
# The caller method gives the call chain in the format | |
# [ "app_mailer.rb:2 in `my_method'", "sub_mailer.rb:5 in `my_method'", script/rails:6 in `<main>"' ] | |
# Look for Mailer classes and pick the last one, at the bottom of the inheritance chain. | |
if caller_string = caller.grep(%r{/app/mailers/.+_mailer\.rb}).last | |
# Extract mailer name and action from that line. | |
mailer, action = caller_string.scan(%r{/app/mailers/(.+_mailer)\.rb:\d+:in `(.+)'}).flatten | |
[ mailer.camelize, action ] | |
end | |
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
class ExampleMailer < ApplicationMailer | |
def bar(customer) | |
custom_mail( | |
to: customer.email, | |
subject: t(:'mailers.example.bar.subject'), | |
text: t(:'mailers.example.bar.body') | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this blog post for a nicer implementation.