BigW Consortium Gitlab

label.rb 2 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 15
  include Referable

16
  DEFAULT_COLOR = '#428BCA'
17

Douwe Maan committed
18 19
  default_value_for :color, DEFAULT_COLOR

20 21
  belongs_to :project
  has_many :label_links, dependent: :destroy
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) }
36

37
  alias_attribute :name, :title
Dmitriy Zaporozhets committed
38

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

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

57 58 59 60 61 62 63 64 65 66 67 68 69 70
  # 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)
71
    if format == :name && !name.include?('"')
72 73 74 75 76 77
      %(#{self.class.reference_prefix}"#{name}")
    else
      "#{self.class.reference_prefix}#{id}"
    end
  end

Dmitriy Zaporozhets committed
78 79 80
  def open_issues_count
    issues.opened.count
  end
81
end