1 require 'erb'
2
3 class ERB
4 module Util
5 HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"' }
6 JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
7
8 # A utility method for escaping HTML tag characters.
9 # This method is also aliased as <tt>h</tt>.
10 #
11 # In your ERb templates, use this method to escape any unsafe content. For example:
12 # <%=h @person.name %>
13 #
14 # ==== Example:
15 # puts html_escape("is a > 0 & a < 10?")
16 # # => is a > 0 & a < 10?
17 def html_escape(s)
18 s = s.to_s
19 if s.html_safe?
20 s
21 else
22 s.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/</, "<").html_safe
23 end
24 end
25
26 undef :h
27 alias h html_escape
28
29 module_function :html_escape
30 module_function :h
31
32 # A utility method for escaping HTML entities in JSON strings.
33 # This method is also aliased as <tt>j</tt>.
34 #
35 # In your ERb templates, use this method to escape any HTML entities:
36 # <%=j @person.to_json %>
37 #
38 # ==== Example:
39 # puts json_escape("is a > 0 & a < 10?")
40 # # => is a \u003E 0 \u0026 a \u003C 10?
41 def json_escape(s)
42 s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
43 end
44
45 alias j json_escape
46 module_function :j
47 module_function :json_escape
48 end
49 end
50
51 class Object
52 def html_safe?
53 false
54 end
55 end
56
57 class Fixnum
58 def html_safe?
59 true
60 end
61 end
62
63 module ActiveSupport #:nodoc:
64 class SafeBuffer < String
65 def +(other)
66 dup.concat(other)
67 end
68
69 def html_safe?
70 true
71 end
72
73 def html_safe
74 self
75 end
76
77 def to_s
78 self
79 end
80
81 def to_yaml(*args)
82 to_str.to_yaml(*args)
83 end
84 end
85 end
86
87 class String
88 alias safe_concat concat
89
90 def as_str
91 self
92 end
93
94 def html_safe
95 ActiveSupport::SafeBuffer.new(self)
96 end
97
98 def html_safe?
99 false
100 end
101 end