diff --git a/app/models/answer.rb b/app/models/answer.rb index 080ec498..f5bf0af9 100644 --- a/app/models/answer.rb +++ b/app/models/answer.rb @@ -3,4 +3,8 @@ class Answer < ActiveRecord::Base belongs_to :question has_many :comments, dependent: :destroy has_many :smiles, dependent: :destroy + + def notification_type(*_args) + Notifications::QuestionAnswered + end end diff --git a/app/models/inbox.rb b/app/models/inbox.rb index 5c664c4a..204190bf 100644 --- a/app/models/inbox.rb +++ b/app/models/inbox.rb @@ -6,6 +6,7 @@ class Inbox < ActiveRecord::Base answer = Answer.create!(content: answer, user: user, question: self.question) + Notification.notify self.question.user, answer user.increment! :answered_count self.question.increment! :answer_count self.destroy diff --git a/app/models/notification.rb b/app/models/notification.rb index b4b4b8f1..20e9ebfe 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -1,2 +1,29 @@ class Notification < ActiveRecord::Base + belongs_to :recipient, class_name: 'User' + belongs_to :target, :polymorphic => true + + class << self + def for(recipient, options={}) + self.where(options.merge!(recipient: recipient)).order(:updated_at).reverse_order + end + + def notify(recipient, target) + return nil unless target.respond_to? :notification_type + + notif_type = target.notification_type + return nil unless notif_type + + make_notification(recipient, target, notif_type) + end + + private + + def make_notification(recipient, target, notification_type) + n = notification_type.new(target: target, + recipient: recipient, + new: true) + n.save! + n + end + end end diff --git a/app/models/user.rb b/app/models/user.rb index a34029fe..905c5c50 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -21,6 +21,7 @@ class User < ActiveRecord::Base has_many :followers, through: :passive_relationships, source: :source has_many :smiles has_many :services + has_many :notifications, foreign_key: :recipient_id SCREEN_NAME_REGEX = /\A[a-zA-Z0-9_]{1,16}\z/ WEBSITE_REGEX = /https?:\/\/([A-Za-z.\-]+)\/?(?:.*)/i diff --git a/app/views/notifications/index.html.haml b/app/views/notifications/index.html.haml index 2e9e9b1e..4fb6fae7 100644 --- a/app/views/notifications/index.html.haml +++ b/app/views/notifications/index.html.haml @@ -2,6 +2,24 @@ = render 'notification_tabs' .col-md-9.col-xs-12.col-sm-9 %ul.list-group + - Notification.for(current_user).each do |notification| + %li.list-group-item + .media + .pull-left + %img.notification--img + .media-body + - case notification.target_type + - when "Answer" + %h6.media-heading.notification--user + = notification.target.user.screen_name + %p.notification--text + answered + %a{href: show_user_answer_path(username: notification.target.user.screen_name, id: notification.target.id)} + your question + = time_ago_in_words notification.target.created_at + ago + .notification--icon + %i.fa.fa-exclamation %li.list-group-item .media .pull-left