Skip to content

Instantly share code, notes, and snippets.

@terry90
Last active April 25, 2016 12:17
Show Gist options
  • Save terry90/b89874b63998d06dbe3350dc14507a08 to your computer and use it in GitHub Desktop.
Save terry90/b89874b63998d06dbe3350dc14507a08 to your computer and use it in GitHub Desktop.
Notification system (with mailer) for Rails 4
# SEE THE GEM https://github.com/terry90/user_notif
# config/application.rb
config.autoload_paths += %W(#{config.root}/app/models/notifications)
# app/models/notifications/custom_notif.rb
class WelcomeNotif < Notif
def target=(t)
raise BadTypeNotification unless t.class == User # Create your exception in ModelException class (included in notif.rb)
super(t)
end
def email_template
'welcome_notif'
end
def subject_email
I18n.t('notif.welcome.subject')
end
end
<%# app/views/notifications/mailer/generic_notif.html.erb %>
Your mail here:
Hello <%= @user.firstname %>
# db/migrate/migration_xxxxx.rb
class CreateNotifs < ActiveRecord::Migration
def change
create_table :notifs do |t|
# Target is the object of the notification (like a Project, Donation or User)
t.references :target, polymorphic: true, index: true
t.belongs_to :user, index: true
t.boolean :unread, index: true, default: true
t.string :type
t.timestamps
end
end
end
# app/models/notif.rb
# A notification must inherit from this and overload methods
class Notif < ActiveRecord::Base
include ModelExceptions # Basic exceptions
belongs_to :target, polymorphic: true
belongs_to :user
after_create :notify_email
def email?
true
end
def email_template
'generic_notif'
end
def subject_email
I18n.t('notif.generic.subject')
end
private
def notify_email
return unless email?
NotifMailer.delay.notif_email(self.id)
end
end
# app/mailers/notif_mailer.rb
class NotifMailer < ApplicationMailer
include DefaultUrlOptions
def notif_email(notif_id)
notif = Notif.find(notif_id)
@target = notif.target || raise('No target in notification mailer')
@user = notif.user
roadie_mail(
to: @user.email,
subject: notif.subject_email,
template_path: 'notifications/mailer',
template_name: notif.email_template
)
end
end
def something
# Do things
InfosNeededNotif.create(target: @project, user: current_user)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment