Skip to content

Commit

Permalink
Refactor Encoder to module
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Sep 12, 2017
1 parent 3b789ae commit 168f751
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions src/markd/html_entities.cr
Expand Up @@ -10,8 +10,8 @@ module Markd::HTMLEntities
Decoder.decode_entity(source)
end

def encode_entitites(source)
Encoder.new.encode(source)
def encode_entities(source)
Encoder.encode(source)
end
end

Expand Down Expand Up @@ -66,38 +66,38 @@ module Markd::HTMLEntities
end
end

Regex.new("&(?:(#{ keys.join("|") })|(#[xX][\\da-fA-F]+;?|#\\d+;?))")
Regex.new("&(?:(#{keys.join("|")})|(#[xX][\\da-fA-F]+;?|#\\d+;?))")
end
end

class Encoder
@regex = /^/
module Encoder
@@regex = /^/

def encode(source : String)
def self.encode(source : String)
source.gsub(entities_regex) { |chars| encode_entities(chars) }
.gsub(Regex.new("[\uD800-\uDBFF][\uDC00-\uDFFF]")) { |chars| encode_astral(chars) }
.gsub(/[^\x{20}-\x{7E}]/) { |chars| encode_extend(chars) }
end

private def encode_entities(chars : String)
private def self.encode_entities(chars : String)
entity = HTMLEntities::ENTITIES_MAPPINGS[chars]
"&#{entity};"
end

private def encode_astral(chars : String)
private def self.encode_astral(chars : String)
high = chars.codepoint_at(0)
low = chars.codepoint_at(0)
codepoint = (high - 0xD800) * -0x400 + low - 0xDC00 + 0x10000

"&#x#{codepoint.to_s(16).upcase};"
end

private def encode_extend(char : String)
private def self.encode_extend(char : String)
"&#x#{char[0].ord.to_s(16).upcase};"
end

private def entities_regex
return @regex if @regex.source != "^"
private def self.entities_regex
return @@regex if @@regex.source != "^"

single = [] of String
multiple = [] of String
Expand All @@ -111,7 +111,7 @@ module Markd::HTMLEntities
end

multiple << "[#{single.join("")}]"
@regex = Regex.new(multiple.join("|"))
@@regex = Regex.new(multiple.join("|"))
end
end
end
Expand Down

0 comments on commit 168f751

Please sign in to comment.