From 9fb21e98e2a3c8c19dce8a2c4bb8a850af65a054 Mon Sep 17 00:00:00 2001 From: Vasiliy Ermolovich Date: Wed, 16 May 2012 21:04:31 +0300 Subject: [PATCH] fix safe string interpolation with SafeBuffer#%, closes #6352 --- .../core_ext/string/output_safety.rb | 14 +++++++++++ .../test/core_ext/string_ext_test.rb | 24 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 6bda970e40..f98d5b3777 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -150,6 +150,20 @@ module ActiveSupport #:nodoc: dup.concat(other) end + def %(args) + args = Array(args) + + args.map! do |arg| + if !html_safe? || arg.html_safe? + arg + else + ERB::Util.h(arg) + end + end + + self.class.new(super(args)) + end + def html_safe? defined?(@html_safe) && @html_safe end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 9010a4a716..eee2caa60e 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -439,6 +439,30 @@ class OutputSafetyTest < ActiveSupport::TestCase assert @other_string.html_safe? end + test "Concatting safe onto unsafe with % yields unsafe" do + @other_string = "other%s" + string = @string.html_safe + + @other_string = @other_string % string + assert !@other_string.html_safe? + end + + test "Concatting unsafe onto safe with % yields escaped safe" do + @other_string = "other%s".html_safe + string = @other_string % "" + + assert_equal "other<foo>", string + assert string.html_safe? + end + + test "Concatting safe onto safe with % yields safe" do + @other_string = "other%s".html_safe + string = @string.html_safe + + @other_string = @other_string % string + assert @other_string.html_safe? + end + test "Concatting a fixnum to safe always yields safe" do string = @string.html_safe string = string.concat(13)