Read about our upcoming Code of Conduct on this issue

label.rb 2.08 KB
Newer Older
Dmitriy Zaporozhets's avatar
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
15
  include Referable

16
  DEFAULT_COLOR = '#428BCA'
17

Douwe Maan's avatar
Douwe Maan committed
18
19
  default_value_for :color, DEFAULT_COLOR

20
21
  belongs_to :project
  has_many :label_links, dependent: :destroy
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
22
  has_many :issues, through: :label_links, source: :target, source_type: 'Issue'
23

24
  validates :color,
25
            format: { with: /\A#[0-9A-Fa-f]{6}\Z/ },
26
            allow_blank: false
27
  validates :project, presence: true
28

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

35
  default_scope { order(title: :asc) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
36

Robert Schilling's avatar
Robert Schilling committed
37
  alias_attribute :name, :title
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
38

39
40
41
42
  def self.reference_prefix
    '~'
  end

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  # Pattern used to extract label references from text
  #
  # TODO (rspeicher): Limit to double quotes (meh) or disallow single quotes in label names (bad).
  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
          ['"][^&\?,]+['"]   # String-based multi-word label surrounded in quotes
        )
      )
    }x
  end

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  # 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
      %(#{self.class.reference_prefix}"#{name}")
    else
      "#{self.class.reference_prefix}#{id}"
    end
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
80
81
82
  def open_issues_count
    issues.opened.count
  end
83
end