BigW Consortium Gitlab

label.rb 2.37 KB
Newer Older
Dmitriy Zaporozhets committed
1 2 3 4 5 6 7 8 9 10 11 12
# == Schema Information
#
# Table name: labels
#
#  id         :integer          not null, primary key
#  title      :string(255)
#  color      :string(255)
#  project_id :integer
#  created_at :datetime
#  updated_at :datetime
#

13
class Label < ActiveRecord::Base
14
  include Referable
15 16
  # Represents a "No Label" state used for filtering Issues and Merge
  # Requests that have no label assigned.
17 18 19
  LabelStruct = Struct.new(:title, :name)
  None = LabelStruct.new('No Label', 'No Label')
  Any = LabelStruct.new('Any', '')
20

21
  DEFAULT_COLOR = '#428BCA'
22

Douwe Maan committed
23 24
  default_value_for :color, DEFAULT_COLOR

25 26
  belongs_to :project
  has_many :label_links, dependent: :destroy
Dmitriy Zaporozhets committed
27
  has_many :issues, through: :label_links, source: :target, source_type: 'Issue'
28

29
  validates :color,
30
            format: { with: /\A#[0-9A-Fa-f]{6}\Z/ },
31
            allow_blank: false
Valery Sizov committed
32
  validates :project, presence: true, unless: Proc.new { |service| service.template? }
33

34
  # Don't allow '?', '&', and ',' for label titles
35 36
  validates :title,
            presence: true,
37
            format: { with: /\A[^&\?,]+\z/ },
38
            uniqueness: { scope: :project_id }
39

40
  default_scope { order(title: :asc) }
41

Valery Sizov committed
42 43
  scope :templates, ->  { where(template: true) }

44
  alias_attribute :name, :title
Dmitriy Zaporozhets committed
45

46 47 48 49
  def self.reference_prefix
    '~'
  end

50 51 52 53 54
  # Pattern used to extract label references from text
  def self.reference_pattern
    %r{
      #{reference_prefix}
      (?:
55
        (?<label_id>\d+) | # Integer-based label ID, or
56
        (?<label_name>
57 58
          [A-Za-z0-9_-]+ | # String-based single-word label title, or
          "[^&\?,]+"       # String-based multi-word label surrounded in quotes
59 60 61 62 63
        )
      )
    }x
  end

64 65 66 67 68 69 70 71 72 73 74 75 76 77
  # Returns the String necessary to reference this Label in Markdown
  #
  # format - Symbol format to use (default: :id, optional: :name)
  #
  # Note that its argument differs from other objects implementing Referable. If
  # a non-Symbol argument is given (such as a Project), it will default to :id.
  #
  # Examples:
  #
  #   Label.first.to_reference        # => "~1"
  #   Label.first.to_reference(:name) # => "~\"bug\""
  #
  # Returns a String
  def to_reference(format = :id)
78
    if format == :name && !name.include?('"')
79 80 81 82 83 84
      %(#{self.class.reference_prefix}"#{name}")
    else
      "#{self.class.reference_prefix}#{id}"
    end
  end

Dmitriy Zaporozhets committed
85 86 87
  def open_issues_count
    issues.opened.count
  end
Valery Sizov committed
88 89 90 91

  def template?
    template
  end
92
end