From 5bc8bbbaa2522f233a58eba12c4089bebbcfa2b9 Mon Sep 17 00:00:00 2001 From: Frederic Merizen Date: Tue, 5 Feb 2019 15:25:54 +0100 Subject: [PATCH] [#3356] Let tags handle their own substitution --- .../concerns/tags_substitution_concern.rb | 20 +++++++++---------- app/models/type_de_champ.rb | 8 ++++++-- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/app/models/concerns/tags_substitution_concern.rb b/app/models/concerns/tags_substitution_concern.rb index c312f6782..285f34e25 100644 --- a/app/models/concerns/tags_substitution_concern.rb +++ b/app/models/concerns/tags_substitution_concern.rb @@ -195,35 +195,33 @@ module TagsSubstitutionConcern def replace_type_de_champ_tags(text, tags, dossier_champs) tags.inject(text) do |acc, tag| - champ = dossier_champs - .detect { |dossier_champ| dossier_champ.libelle == tag[:libelle] } - - replace_tag(acc, tag, champ) + replace_tag(acc, tag, dossier_champs) end end def replace_tags_with_values_from_data(text, tags, data) if data.present? tags.inject(text) do |acc, tag| - if tag.key?(:target) - value = data.send(tag[:target]) - else - value = instance_exec(data, &tag[:lambda]) - end - replace_tag(acc, tag, value) + replace_tag(acc, tag, data) end else text end end - def replace_tag(text, tag, value) + def replace_tag(text, tag, data) libelle = Regexp.quote(tag[:libelle]) # allow any kind of space (non-breaking or other) in the tag’s libellé to match any kind of space in the template # (the '\\ |' is there because plain ASCII spaces were escaped by preceding Regexp.quote) libelle.gsub!(/\\ |[[:blank:]]/, "[[:blank:]]") + if tag.key?(:target) + value = data.send(tag[:target]) + else + value = instance_exec(data, &tag[:lambda]) + end + text.gsub(/--#{libelle}--/, value.to_s) end end diff --git a/app/models/type_de_champ.rb b/app/models/type_de_champ.rb index d7faa2904..ee34fc0bb 100644 --- a/app/models/type_de_champ.rb +++ b/app/models/type_de_champ.rb @@ -175,10 +175,14 @@ class TypeDeChamp < ApplicationRecord end def tags_for_template + l = libelle [ { - libelle: libelle, - description: description + libelle: l, + description: description, + lambda: -> (champs) { + champs.detect { |champ| champ.libelle == l } + } } ] end