gitlab-org--gitlab-foss/lib/banzai/reference_extractor.rb
Yorick Peterse daad7144ec
Support Markdown rendering using multiple projects
This refactors the Markdown pipeline so it supports the rendering of
multiple documents that may belong to different projects. An example of
where this happens is when displaying the event feed of a group. In this
case we retrieve events for all projects in the group. Previously we
would group events per project and render these chunks separately, but
this would result in many SQL queries being executed. By extending the
Markdown pipeline to support this out of the box we can drastically
reduce the number of SQL queries.

To achieve this we introduce a new object to the pipeline:
Banzai::RenderContext. This object simply wraps two other objects: an
optional Project instance, and an optional User instance. On its own
this wouldn't be very helpful, but a RenderContext can also be used to
associate HTML documents with specific Project instances. This work is
done in Banzai::ObjectRenderer and allows us to reuse as many queries
(and results) as possible.
2018-04-11 14:10:19 +02:00

35 lines
958 B
Ruby

module Banzai
# Extract possible GFM references from an arbitrary String for further processing.
class ReferenceExtractor
def initialize
@texts_and_contexts = []
end
def analyze(text, context = {})
@texts_and_contexts << { text: text, context: context }
end
def references(type, project, current_user = nil)
context = RenderContext.new(project, current_user)
processor = Banzai::ReferenceParser[type].new(context)
processor.process(html_documents)
end
def reset_memoized_values
@html_documents = nil
@texts_and_contexts = []
end
private
def html_documents
# This ensures that we don't memoize anything until we have a number of
# text blobs to parse.
return [] if @texts_and_contexts.empty?
@html_documents ||= Renderer.cache_collection_render(@texts_and_contexts)
.map { |html| Nokogiri::HTML.fragment(html) }
end
end
end