Read about our upcoming Code of Conduct on this issue

milestone_reference_filter.rb 2.09 KB
Newer Older
1
2
3
4
module Banzai
  module Filter
    # HTML filter that replaces milestone references with links.
    class MilestoneReferenceFilter < AbstractReferenceFilter
5
6
      self.reference_type = :milestone

7
8
9
10
11
      def self.object_class
        Milestone
      end

      def find_object(project, id)
12
        project.milestones.find_by(iid: id)
13
14
      end

15
      def references_in(text, pattern = Milestone.reference_pattern)
16
17
18
19
20
        # We'll handle here the references that follow the `reference_pattern`.
        # Other patterns (for example, the link pattern) are handled by the
        # default implementation.
        return super(text, pattern) if pattern != Milestone.reference_pattern

21
        text.gsub(pattern) do |match|
22
          milestone = find_milestone($~[:project], $~[:namespace], $~[:milestone_iid], $~[:milestone_name])
23
24

          if milestone
25
            yield match, milestone.iid, $~[:project], $~[:namespace], $~
26
27
28
29
30
31
          else
            match
          end
        end
      end

32
33
34
35
      def find_milestone(project_ref, namespace_ref, milestone_id, milestone_name)
        project_path = full_project_path(namespace_ref, project_ref)
        project = project_from_ref(project_path)

36
37
38
39
40
41
42
43
44
45
46
47
48
49
        return unless project

        milestone_params = milestone_params(milestone_id, milestone_name)
        project.milestones.find_by(milestone_params)
      end

      def milestone_params(iid, name)
        if name
          { name: name.tr('"', '') }
        else
          { iid: iid.to_i }
        end
      end

50
      def url_for_object(milestone, project)
51
        h = Gitlab::Routing.url_helpers
52
53
54
        h.namespace_project_milestone_url(project.namespace, project, milestone,
                                        only_path: context[:only_path])
      end
55

56
      def object_link_text(object, matches)
57
58
59
60
61
        milestone_link = escape_once(super)
        reference = object.project.to_reference(project)

        if reference.present?
          "#{milestone_link} <i>in #{reference}</i>".html_safe
62
        else
63
          milestone_link
64
65
        end
      end
66
67
68
69

      def object_link_title(object)
        nil
      end
70
71
72
    end
  end
end