diff options
-rw-r--r-- | lib/i18n_fixes.rb | 14 | ||||
-rw-r--r-- | spec/lib/i18n_interpolation.rb | 38 |
2 files changed, 49 insertions, 3 deletions
diff --git a/lib/i18n_fixes.rb b/lib/i18n_fixes.rb index dae5437b3..2222fc2f9 100644 --- a/lib/i18n_fixes.rb +++ b/lib/i18n_fixes.rb @@ -10,7 +10,7 @@ # convention. def _(key, options = {}) - translation = FastGettext._(key) || key + translation = (FastGettext._(key) || key).html_safe gettext_interpolate(translation, options) end @@ -20,7 +20,9 @@ MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ def gettext_interpolate(string, values) return string unless string.is_a?(String) if values.is_a?(Hash) - string.gsub(MATCH) do + # $1, $2 don't work with SafeBuffer so casting to string as workaround + safe = string.html_safe? + string = string.to_str.gsub(MATCH) do escaped, pattern, key = $1, $2, $2.to_sym if escaped @@ -30,9 +32,15 @@ def gettext_interpolate(string, values) elsif !values.include?(key) raise I18n::MissingInterpolationArgument.new(pattern, string) else - values[key].to_s + v = values[key].to_s + if safe && !v.html_safe? + ERB::Util.h(v) + else + v + end end end + safe ? string.html_safe : string else reserved_keys = if defined?(I18n::RESERVED_KEYS) # rails 3+ I18n::RESERVED_KEYS diff --git a/spec/lib/i18n_interpolation.rb b/spec/lib/i18n_interpolation.rb index 8c86413ad..3fb72ff03 100644 --- a/spec/lib/i18n_interpolation.rb +++ b/spec/lib/i18n_interpolation.rb @@ -11,5 +11,43 @@ describe "when using i18n" do result = _('Hello {{dip}}', :dip => 'hummus') result.should == 'Hello hummus' end + + it "should assume that simple translations are always html safe" do + _("Hello").should be_html_safe + end + end +describe "gettext_interpolate" do + context "html unsafe string" do + let(:string) { "Hello {{a}}" } + + it "should give an unsafe result" do + result = gettext_interpolate(string, :a => "foo") + result.should == "Hello foo" + result.should_not be_html_safe + end + + it "should give an unsafe result" do + result = gettext_interpolate(string, :a => "foo".html_safe) + result.should == "Hello foo" + result.should_not be_html_safe + end + end + + context "html safe string" do + let(:string) { "Hello {{a}}".html_safe } + + it "should quote the input if it's unsafe" do + result = gettext_interpolate(string, :a => "foo&") + result.should == "Hello foo&" + result.should be_html_safe + end + + it "should not quote the input if it's safe" do + result = gettext_interpolate(string, :a => "foo&".html_safe) + result.should == "Hello foo&" + result.should be_html_safe + end + end +end |