summaryrefslogtreecommitdiff
path: root/app/models/list.rb
blob: 4edcfa78835abf232757059ae9fee9724ab54930 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class List < ActiveRecord::Base
  belongs_to :board
  belongs_to :label

  enum list_type: { backlog: 0, label: 1, closed: 2, assignee: 3 }

  validates :board, :list_type, presence: true
  validates :label, :position, presence: true, if: :label?
  validates :label_id, uniqueness: { scope: :board_id }, if: :label?
  validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, if: :movable?

  before_destroy :can_be_destroyed

  scope :destroyable, -> { where(list_type: list_types.slice(*destroyable_types).values) }
  scope :movable, -> { where(list_type: list_types.slice(*movable_types).values) }

  class << self
    def destroyable_types
      [:label]
    end

    def movable_types
      [:label]
    end
  end

  def destroyable?
    label?
  end

  def movable?
    label?
  end

  def title
    label? ? label.name : list_type.humanize
  end

  def as_json(options = {})
    super(options).tap do |json|
      if options.key?(:label)
        json[:label] = label.as_json(
          project: board.project,
          only: [:id, :title, :description, :color],
          methods: [:text_color]
        )
      end
    end
  end

  private

  def can_be_destroyed
    destroyable?
  end
end