list.rb 1.51 KB
Newer Older
1 2
# frozen_string_literal: true

3
class List < ApplicationRecord
4 5
  belongs_to :board
  belongs_to :label
6
  include Importable
7

8
  enum list_type: { backlog: 0, label: 1, closed: 2, assignee: 3, milestone: 4 }
9

10
  validates :board, :list_type, presence: true, unless: :importing?
11
  validates :label, :position, presence: true, if: :label?
12
  validates :label_id, uniqueness: { scope: :board_id }, if: :label?
13
  validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, if: :movable?
14

15 16
  before_destroy :can_be_destroyed

17 18
  scope :destroyable, -> { where(list_type: list_types.slice(*destroyable_types).values) }
  scope :movable, -> { where(list_type: list_types.slice(*movable_types).values) }
19
  scope :preload_associations, -> { preload(:board, :label) }
20
  scope :ordered, -> { order(:list_type, :position) }
21 22 23 24 25 26 27 28 29 30

  class << self
    def destroyable_types
      [:label]
    end

    def movable_types
      [:label]
    end
  end
31 32

  def destroyable?
33
    self.class.destroyable_types.include?(list_type&.to_sym)
34
  end
35

36
  def movable?
37
    self.class.movable_types.include?(list_type&.to_sym)
38 39
  end

40
  def title
41
    label? ? label.name : list_type.humanize
42
  end
43

44 45
  def as_json(options = {})
    super(options).tap do |json|
46
      if options.key?(:label)
47 48
        json[:label] = label.as_json(
          project: board.project,
49 50
          only: [:id, :title, :description, :color],
          methods: [:text_color]
51 52 53 54 55
        )
      end
    end
  end

56 57 58
  private

  def can_be_destroyed
59
    throw(:abort) unless destroyable?
60
  end
61
end