Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created December 25, 2010 16:58
Show Gist options
  • Save qoobaa/754948 to your computer and use it in GitHub Desktop.
Save qoobaa/754948 to your computer and use it in GitHub Desktop.
Using ActionMailer for internal messaging
class UserNotifier < ActionMailer::Base
# sample message
def some_message(user)
from %Q{"Internal Messaging System"}
recipients user.email
subject "This is internal message"
body :user => user
end
# sample message notification
def message_notification(message)
from %Q{"MyAppName.com mailer"}
recipients message.recipient.email
subject "You've new message in your inbox"
body :user => user
end
private
# if the called method has "deliver_internal_"
# prefix, use notify method to deliver message
def self.method_missing(method_name, *args)
if method_name.to_s =~ /^deliver_internal_([_a-z]\w*)/
new($1, *args).send(:deliver_internal)
else
super
end
end
# deliver message to user using internal messaging
def deliver_internal
users = User.find_all_by_email(@mail.to)
from = @mail.from.first[1..-2] # remove quotes
users.each do |user|
Message.create!(:recipient => user,
:subject => @mail.subject,
:body => @mail.body,
:sender_name => from)
end
end
end
class Message < ActiveRecord::Base
after_create :deliver_notification
belongs_to :recipient, :class_name => "User"
private
def deliver_notification
# deliver message notification email (external)
# if the user wants it
if recipient.wants_message_notifications?
UserNotifier.deliver_message_notification(self)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment