Skip to content

Instantly share code, notes, and snippets.

@henrik
Created May 23, 2012 14:37
Show Gist options
  • Select an option

  • Save henrik/2775581 to your computer and use it in GitHub Desktop.

Select an option

Save henrik/2775581 to your computer and use it in GitHub Desktop.
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

henrik commented Aug 7, 2012

Copy link
Copy Markdown
Author

See this blog post for a nicer implementation.

@flevour

flevour commented Aug 5, 2014

Copy link
Copy Markdown

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