diff options
Diffstat (limited to 'app/helpers/safe_format_helper.rb')
-rw-r--r-- | app/helpers/safe_format_helper.rb | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/app/helpers/safe_format_helper.rb b/app/helpers/safe_format_helper.rb new file mode 100644 index 00000000000..c79e8b50a1a --- /dev/null +++ b/app/helpers/safe_format_helper.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +module SafeFormatHelper + # Returns a HTML-safe string where +format+ and +args+ are escaped via + # `html_escape` if they are not marked as HTML-safe. + # + # Argument +format+ must not be marked as HTML-safe via `.html_safe`. + # + # Example: + # safe_format('Some %{open}bold%{close} text.', open: '<strong>'.html_safe, close: '</strong>'.html_safe) + # # => 'Some <strong>bold</strong>' + # safe_format('See %{user_input}', user_input: '<b>bold</b>') + # # => 'See <b>bold</b> + # + def safe_format(format, **args) + raise ArgumentError, 'Argument `format` must not be marked as html_safe!' if format.html_safe? + + format( + html_escape(format), + args.transform_values { |value| html_escape(value) } + ).html_safe + end +end |