Skip to content

Commit

Permalink
Add documentation to the HTML module
Browse files Browse the repository at this point in the history
  • Loading branch information
dylandrop authored and asterite committed Dec 13, 2016
1 parent 278ffff commit 51e2e76
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/html.cr
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# Handles encoding and decoding of HTML entities.
module HTML
SUBSTITUTIONS = {
'!' => "!",
Expand All @@ -21,16 +22,39 @@ module HTML
'\u{a0}' => " ",
}

# Encodes a string with HTML entity substitutions.
#
# ```
# require "html"
#
# HTML.escape("Crystal & You") # => "Crystal & You"
# ```
def self.escape(string : String) : String
string.gsub(SUBSTITUTIONS)
end

# Encodes a string to HTML, but writes to the IO instance provided.
#
# ```
# require "html"
#
# io = IO::Memory.new
# HTML.escape("Crystal & You", io) # => "Crystal & You"
# io.to_s # => "Crystal & You"
# ```
def self.escape(string : String, io : IO)
string.each_char do |char|
io << SUBSTITUTIONS.fetch(char, char)
end
end

# Decodes a string that contains HTML entities.
#
# ```
# require "html"
#
# HTML.unescape("Crystal &amp; You") # => "Crystal & You"
# ```
def self.unescape(string : String)
return string unless string.includes? '&'

Expand Down

0 comments on commit 51e2e76

Please sign in to comment.