Skip to content

Instantly share code, notes, and snippets.

@henrik
Created May 23, 2012 14:37
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Setting SendGrid category to ActionMailer mailer and action in Rails 3.
# 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
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
@henrik
Copy link
Author

henrik commented Aug 7, 2012

See this blog post for a nicer implementation.

@flevour
Copy link

flevour commented Aug 5, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment