refactor: be explicite with memoization

This commit is contained in:
simon lehericey 2024-05-15 10:30:51 +02:00
parent 420520489d
commit e8a175d310
No known key found for this signature in database
GPG key ID: CDE670D827C7B3C5
2 changed files with 10 additions and 6 deletions

View file

@ -275,7 +275,7 @@ module TagsSubstitutionConcern
used_tags_and_libelle_for(text).map { _1.first.nil? ? _1.second : _1.first } used_tags_and_libelle_for(text).map { _1.first.nil? ? _1.second : _1.first }
end end
def tags_substitutions(tags_and_libelles, dossier, escape: true) def tags_substitutions(tags_and_libelles, dossier, escape: true, memoize: false)
# NOTE: # NOTE:
# - tags_and_libelles est un simple Set de couples (tag_id, libelle) (pas la même structure que dans replace_tags) # - tags_and_libelles est un simple Set de couples (tag_id, libelle) (pas la même structure que dans replace_tags)
# - dans `replace_tags`, on fait référence à des tags avec ou sans id, mais pas ici, # - dans `replace_tags`, on fait référence à des tags avec ou sans id, mais pas ici,
@ -283,16 +283,20 @@ module TagsSubstitutionConcern
@escape_unsafe_tags = escape @escape_unsafe_tags = escape
if @flat_tags.nil? flat_tags = if memoize && @flat_tags.present?
@flat_tags = available_tags(dossier) @flat_tags
else
available_tags(dossier)
.flatten .flatten
.then { tags_for_dossier_state(_1) } .then { tags_for_dossier_state(_1) }
.index_by { _1[:id] } .index_by { _1[:id] }
end end
@flat_tags = flat_tags if memoize
tags_and_libelles.each_with_object({}) do |(tag_id, libelle), substitutions| tags_and_libelles.each_with_object({}) do |(tag_id, libelle), substitutions|
substitutions[tag_id] = if @flat_tags[tag_id].present? substitutions[tag_id] = if flat_tags[tag_id].present?
replace_tag(@flat_tags[tag_id], dossier) replace_tag(flat_tags[tag_id], dossier)
else # champ not in dossier, for example during preview on draft revision else # champ not in dossier, for example during preview on draft revision
libelle libelle
end end

View file

@ -67,7 +67,7 @@ class ExportTemplate < ApplicationRecord
def render_attributes_for(content_for, dossier, attachment = nil) def render_attributes_for(content_for, dossier, attachment = nil)
tiptap = TiptapService.new tiptap = TiptapService.new
used_tags = tiptap.used_tags_and_libelle_for(content_for.deep_symbolize_keys) used_tags = tiptap.used_tags_and_libelle_for(content_for.deep_symbolize_keys)
substitutions = tags_substitutions(used_tags, dossier, escape: false) substitutions = tags_substitutions(used_tags, dossier, escape: false, memoize: true)
substitutions['original-filename'] = attachment.filename.base if attachment substitutions['original-filename'] = attachment.filename.base if attachment
tiptap.to_path(content_for.deep_symbolize_keys, substitutions) tiptap.to_path(content_for.deep_symbolize_keys, substitutions)
end end