todo.rb 1.79 KB
Newer Older
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
1 2
# == Schema Information
#
3
# Table name: todos
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
4 5 6 7 8 9 10
#
#  id          :integer          not null, primary key
#  user_id     :integer          not null
#  project_id  :integer          not null
#  target_id   :integer          not null
#  target_type :string           not null
#  author_id   :integer
11
#  note_id     :integer
12
#  action      :integer          not null
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
13 14 15 16 17
#  state       :string           not null
#  created_at  :datetime
#  updated_at  :datetime
#

18
class Todo < ActiveRecord::Base
19
  ASSIGNED  = 1
20
  MENTIONED = 2
21

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
22
  belongs_to :author, class_name: "User"
23
  belongs_to :note
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
24 25 26 27
  belongs_to :project
  belongs_to :target, polymorphic: true, touch: true
  belongs_to :user

28 29
  delegate :name, :email, to: :author, prefix: true, allow_nil: true

30 31 32
  validates :action, :project, :target_type, :user, presence: true
  validates :target_id, presence: true, if: ->(t) { t.target_type.present? && t.target_type != 'Commit' }
  validates :commit_id, presence: true, if: ->(t) { t.target_type.present? && t.target_type == 'Commit' }
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
33

34 35 36 37 38
  default_scope { reorder(id: :desc) }

  scope :pending, -> { with_state(:pending) }
  scope :done, -> { with_state(:done) }

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
39
  state_machine :state, initial: :pending do
40
    event :done do
41
      transition [:pending, :done] => :done
42 43
    end

Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
44 45 46
    state :pending
    state :done
  end
47

48 49 50 51 52 53
  def body
    if note.present?
      note.note
    else
      target.title
    end
54
  end
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

  def for_commit?
    target_type == "Commit"
  end

  # override to return commits, which are not active record
  def target
    if for_commit?
      project.commit(commit_id)
    else
      super
    end
  # Temp fix to prevent app crash
  # if note commit id doesn't exist
  rescue
    nil
  end

  def to_reference
    if for_commit?
      Commit.truncate_sha(commit_id)
    else
      target.to_reference
    end
  end
Douglas Barbosa Alexandre's avatar
Douglas Barbosa Alexandre committed
80
end