Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 9241

Show
Ignore:
Timestamp:
04/08/08 04:52:01 (8 months ago)
Author:
rick
Message:

add json_escape ERB util to escape html entities in json strings that are output in HTML pages. [rick]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/actionpack/CHANGELOG

    r9234 r9241  
    11*SVN* 
     2 
     3* add json_escape ERB util to escape html entities in json strings that are output in HTML pages. [rick] 
    24 
    35* Provide a helper proxy to access helper methods from outside views. Closes #10839 [Josh Peek] 
  • trunk/actionpack/lib/action_view/template_handlers/erb.rb

    r8689 r9241  
    33class ERB 
    44  module Util 
    5     HTML_ESCAPE = { '&' => '&amp;', '"' => '&quot;', '>' => '&gt;', '<' => '&lt;' } 
     5    HTML_ESCAPE = { '&' => '&amp;',  '>' => '&gt;',   '<' => '&lt;', '"' => '&quot;' } 
     6    JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C'} 
    67 
    78    # A utility method for escaping HTML tag characters. 
     
    1718      s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] } 
    1819    end 
     20 
     21    # A utility method for escaping HTML entities in JSON strings. 
     22    # This method is also aliased as <tt>j</tt>. 
     23    # 
     24    # In your ERb templates, use this method to escape any HTML entities: 
     25    #   <%=j @person.to_json %> 
     26    # 
     27    # ==== Example: 
     28    #   puts json_escape("is a > 0 & a < 10?") 
     29    #   # => is a \u003E 0 \u0026 a \u003C 10? 
     30    def json_escape(s) 
     31      s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] } 
     32    end 
     33 
     34    alias j json_escape 
     35    module_function :j 
     36    module_function :json_escape 
    1937  end 
    2038end 
  • trunk/actionpack/test/template/erb_util_test.rb

    r8564 r9241  
    33class ErbUtilTest < Test::Unit::TestCase 
    44  include ERB::Util 
    5    
    6   def test_amp 
    7     assert_equal '&amp;', html_escape('&') 
    8   end 
    9    
    10   def test_quot 
    11     assert_equal '&quot;', html_escape('"') 
    12   end 
    135 
    14   def test_lt 
    15     assert_equal '&lt;', html_escape('<') 
    16   end 
     6  ERB::Util::HTML_ESCAPE.each do |given, expected| 
     7    define_method "test_html_escape_#{expected.gsub /\W/, ''}" do 
     8      assert_equal expected, html_escape(given) 
     9    end 
    1710 
    18   def test_gt 
    19     assert_equal '&gt;', html_escape('>') 
     11    unless given == '"' 
     12      define_method "test_json_escape_#{expected.gsub /\W/, ''}" do 
     13        assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given) 
     14      end 
     15    end 
    2016  end 
    2117