sent_notification.rb 1.85 KB
Newer Older
Stan Hu's avatar
Stan Hu committed
1 2 3 4 5 6 7
# == Schema Information
#
# Table name: sent_notifications
#
#  id            :integer          not null, primary key
#  project_id    :integer
#  noteable_id   :integer
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
8
#  noteable_type :string
Stan Hu's avatar
Stan Hu committed
9
#  recipient_id  :integer
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
10 11 12
#  commit_id     :string
#  reply_key     :string           not null
#  line_code     :string
Stan Hu's avatar
Stan Hu committed
13 14
#

Douwe Maan's avatar
Douwe Maan committed
15 16 17 18 19
class SentNotification < ActiveRecord::Base
  belongs_to :project
  belongs_to :noteable, polymorphic: true
  belongs_to :recipient, class_name: "User"

Valery Sizov's avatar
Valery Sizov committed
20 21
  validates :project, :recipient, :reply_key, presence: true
  validates :reply_key, uniqueness: true
Douwe Maan's avatar
Douwe Maan committed
22 23
  validates :noteable_id, presence: true, unless: :for_commit?
  validates :commit_id, presence: true, if: :for_commit?
24
  validates :line_code, line_code: true, allow_blank: true
Douwe Maan's avatar
Douwe Maan committed
25

26
  class << self
27 28 29 30
    def reply_key
      SecureRandom.hex(16)
    end

31 32 33 34
    def for(reply_key)
      find_by(reply_key: reply_key)
    end

35
    def record(noteable, recipient_id, reply_key, params = {})
36 37 38 39 40 41 42 43 44 45
      return unless reply_key

      noteable_id = nil
      commit_id = nil
      if noteable.is_a?(Commit)
        commit_id = noteable.id
      else
        noteable_id = noteable.id
      end

46
      params.reverse_merge!(
47 48 49 50 51 52 53
        project:        noteable.project,
        noteable_type:  noteable.class.name,
        noteable_id:    noteable_id,
        commit_id:      commit_id,
        recipient_id:   recipient_id,
        reply_key:      reply_key
      )
54 55 56 57 58 59

      create(params)
    end

    def record_note(note, recipient_id, reply_key, params = {})
      params[:line_code] = note.line_code
60

61
      record(note.noteable, recipient_id, reply_key, params)
62
    end
Douwe Maan's avatar
Douwe Maan committed
63 64
  end

65
  def unsubscribable?
66 67 68
    !for_commit?
  end

Douwe Maan's avatar
Douwe Maan committed
69 70 71 72 73 74
  def for_commit?
    noteable_type == "Commit"
  end

  def noteable
    if for_commit?
Douwe Maan's avatar
Douwe Maan committed
75
      project.commit(commit_id) rescue nil
Douwe Maan's avatar
Douwe Maan committed
76 77 78 79
    else
      super
    end
  end
80 81 82 83

  def to_param
    self.reply_key
  end
Douwe Maan's avatar
Douwe Maan committed
84
end