1- # Handles encoding and decoding of HTML entities .
1+ # Provides HTML escaping and unescaping methods .
22module HTML
3- SUBSTITUTIONS = {
4- '!' => " !" ,
5- '"' => " "" ,
6- '$' => " $" ,
7- '%' => " %" ,
8- '&' => " &" ,
9- '\' ' => " '" ,
10- '(' => " (" ,
11- ')' => " )" ,
12- '=' => " =" ,
13- '>' => " >" ,
14- '<' => " <" ,
15- '+' => " +" ,
16- '@' => " @" ,
17- '[' => " [" ,
18- ']' => " ]" ,
19- '`' => " `" ,
20- '{' => " {" ,
21- '}' => " }" ,
22- '\u{a0}' => " " ,
3+ private SUBSTITUTIONS = {
4+ '&' => " &" ,
5+ '<' => " <" ,
6+ '>' => " >" ,
7+ '"' => " "" ,
8+ '\' ' => " '" ,
239 }
2410
25- # Encodes a string with HTML entity substitutions.
11+ # Escapes special characters in HTML, namely
12+ # `&`, `<`, `>`, `"` and `'`.
2613 #
2714 # ```
2815 # require "html"
@@ -33,25 +20,29 @@ module HTML
3320 string.gsub(SUBSTITUTIONS )
3421 end
3522
36- # Encodes a string to HTML, but writes to the `IO` instance provided.
23+ # Same as `escape(string)` but ouputs the result to
24+ # the given *io*.
3725 #
3826 # ```
3927 # io = IO::Memory.new
4028 # HTML.escape("Crystal & You", io) # => nil
4129 # io.to_s # => "Crystal & You"
4230 # ```
43- def self.escape (string : String , io : IO )
31+ def self.escape (string : String , io : IO ) : Nil
4432 string.each_char do |char |
4533 io << SUBSTITUTIONS .fetch(char, char)
4634 end
4735 end
4836
49- # Decodes a string that contains HTML entities.
37+ # Returns a string where some named and all numeric character references
38+ # (e.g. >, >, &x3e;) in *string* are replaced with the corresponding
39+ # unicode characters. Only these named entities are replaced:
40+ # apos, amp, quot, gt, lt and nbsp.
5041 #
5142 # ```
5243 # HTML.unescape("Crystal & You") # => "Crystal & You"
5344 # ```
54- def self.unescape (string : String )
45+ def self.unescape (string : String ) : String
5546 return string unless string.includes? '&'
5647
5748 string.gsub(/&(apos|amp|quot|gt|lt|nbsp|\# [0-9] +|\# [xX][0-9A-Fa-f] +) ;/ ) do |string , _match |
0 commit comments