BigW Consortium Gitlab

referable.rb 2.05 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# == Referable concern
#
# Contains functionality related to making a model referable in Markdown, such
# as "#1", "!2", "~3", etc.
module Referable
  extend ActiveSupport::Concern

  # Returns the String necessary to reference this object in Markdown
  #
  # from_project - Refering Project object
  #
  # This should be overridden by the including class.
  #
  # Examples:
  #
  #   Issue.first.to_reference               # => "#1"
  #   Issue.last.to_reference(other_project) # => "cross-project#1"
  #
  # Returns a String
20
  def to_reference(_from_project = nil, full:)
21 22 23
    ''
  end

24 25 26 27
  def reference_link_text(from_project = nil)
    to_reference(from_project)
  end

28 29 30 31 32
  included do
    alias_method :non_referable_inspect, :inspect
    alias_method :inspect, :referable_inspect
  end

33 34 35 36 37 38 39 40
  def referable_inspect
    if respond_to?(:id)
      "#<#{self.class.name} id:#{id} #{to_reference(full: true)}>"
    else
      "#<#{self.class.name} #{to_reference(full: true)}>"
    end
  end

41 42 43 44 45 46 47 48 49 50 51 52 53 54
  module ClassMethods
    # The character that prefixes the actual reference identifier
    #
    # This should be overridden by the including class.
    #
    # Examples:
    #
    #   Issue.reference_prefix        # => '#'
    #   MergeRequest.reference_prefix # => '!'
    #
    # Returns a String
    def reference_prefix
      ''
    end
55 56 57 58 59

    # Regexp pattern used to match references to this object
    #
    # This must be overridden by the including class.
    #
60
    # Returns a Regexp
61
    def reference_pattern
62
      raise NotImplementedError, "#{self} does not implement #{__method__}"
63
    end
64

65 66 67 68
    def reference_valid?(reference)
      true
    end

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    def link_reference_pattern(route, pattern)
      %r{
        (?<url>
          #{Regexp.escape(Gitlab.config.gitlab.url)}
          \/#{Project.reference_pattern}
          \/#{Regexp.escape(route)}
          \/#{pattern}
          (?<path>
            (\/[a-z0-9_=-]+)*
          )?
          (?<query>
            \?[a-z0-9_=-]+
            (&[a-z0-9_=-]+)*
          )?
          (?<anchor>\#[a-z0-9_-]+)?
        )
      }x
    end
87 88
  end
end