Skip to content

Instantly share code, notes, and snippets.

@rdetert
Created June 28, 2011 23:54
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 rdetert/1052538 to your computer and use it in GitHub Desktop.
Save rdetert/1052538 to your computer and use it in GitHub Desktop.
Generate Email Body from Controller or Observer to Send via Delayed Job
# controllers/shared/abstract_email_controller.rb
module Shared
class AbstractEmailController < AbstractController::Base
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
include Rails.application.routes.url_helpers
include ActionView::Helpers::AssetTagHelper
# Uncomment if you want to use helpers
# defined in ApplicationHelper in your views
# helper ApplicationHelper
# Make sure your controller can find views
self.view_paths = "app/views"
self.assets_dir = '/app/public'
# You can define custom helper methods to be used in views here
# helper_method :current_admin
# def current_admin; nil; end
def generate_notification_email(post, host = ENV['RAILS_SERVER'])
render :partial => "posts/notification_email", :locals => { :post => post, :host => host }
end
end
end
<%# views/posts/notification_email.html.erb %>
Hey <%= post.user.name %>,
Just letting you know that your post was created swimmingly.
<%= post_path(post) %>
-love,
team
# mailers/post_notification_mail.rb
class PostNotificationMail < ActionMailer::Base
def send_notification(post_id, body)
post = Post.find(post_id)
sender = "notifications@yayteam.com"
recipient = post.user.email
mail(:content_type => "text/html", :from => sender, :to => recipient, :subject => "We've Got Goodies for You!", :body => body )
end
end
# observers/post_observer.rb
#
# Don't forget to load this in application.rb
#
class PostObserver < ActiveRecord::Observer
def after_create(post)
email_body = Shared::AbstractEmailController.new.generate_notification_email(post)
PostNotificationMail.delay.send_notification(post.id, email_body)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment