debian-mirror-gitlab/app/models/concerns/referable.rb

100 lines
2.4 KiB
Ruby
Raw Normal View History

2018-11-20 20:47:30 +05:30
# frozen_string_literal: true
2015-09-11 14:41:01 +05:30
# == 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
#
2018-03-17 18:26:18 +05:30
# from - Referring parent object
2015-09-11 14:41:01 +05:30
#
# 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
2018-03-17 18:26:18 +05:30
def to_reference(_from = nil, full:)
2015-09-11 14:41:01 +05:30
''
end
2020-03-09 13:42:32 +05:30
# If this referable object can serve as the base for the
# reference of child objects (e.g. projects are the base of
# issues), but it is formatted differently, then you may wish
# to override this method.
def to_reference_base(from = nil, full:)
to_reference(from, full: full)
end
2018-03-17 18:26:18 +05:30
def reference_link_text(from = nil)
to_reference(from)
end
included do
alias_method :non_referable_inspect, :inspect
alias_method :inspect, :referable_inspect
2015-12-23 02:04:40 +05:30
end
2017-09-10 17:25:29 +05:30
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
2018-11-20 20:47:30 +05:30
class_methods do
2015-09-11 14:41:01 +05:30
# 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
# Regexp pattern used to match references to this object
#
# This must be overridden by the including class.
#
# Returns a Regexp
def reference_pattern
raise NotImplementedError, "#{self} does not implement #{__method__}"
end
2015-12-23 02:04:40 +05:30
2016-06-22 15:30:34 +05:30
def reference_valid?(reference)
true
end
2015-12-23 02:04:40 +05:30
def link_reference_pattern(route, pattern)
%r{
(?<url>
#{Regexp.escape(Gitlab.config.gitlab.url)}
\/#{Project.reference_pattern}
2019-09-04 21:01:54 +05:30
(?:\/\-)?
2020-03-09 13:42:32 +05:30
\/#{route.is_a?(Regexp) ? route : Regexp.escape(route)}
2015-12-23 02:04:40 +05:30
\/#{pattern}
(?<path>
2021-01-03 14:25:43 +05:30
(\/[a-z0-9_=-]+)*\/*
2015-12-23 02:04:40 +05:30
)?
(?<query>
\?[a-z0-9_=-]+
(&[a-z0-9_=-]+)*
)?
(?<anchor>\#[a-z0-9_-]+)?
)
}x
end
2015-09-11 14:41:01 +05:30
end
end