summaryrefslogtreecommitdiff
path: root/app/models/label.rb
blob: 1bb4b5f55cfa6e89f32e3d354e0abd9b3ad6c83a (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# == 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
#

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

  DEFAULT_COLOR = '#428BCA'

  default_value_for :color, DEFAULT_COLOR

  belongs_to :project
  has_many :label_links, dependent: :destroy
  has_many :issues, through: :label_links, source: :target, source_type: 'Issue'

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

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

  default_scope { order(title: :asc) }

  scope :templates, ->  { where(template: true) }

  alias_attribute :name, :title

  def self.reference_prefix
    '~'
  end

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

  # 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)
    if format == :name && !name.include?('"')
      %(#{self.class.reference_prefix}"#{name}")
    else
      "#{self.class.reference_prefix}#{id}"
    end
  end

  def open_issues_count
    issues.opened.count
  end

  def template?
    template
  end
end