Class: Canon::Xml::CharacterEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/canon/xml/character_encoder.rb

Overview

Character encoder for C14N 1.1 Handles UTF-8 encoding and character reference encoding per spec

Constant Summary collapse

TEXT_ESCAPABLE =

Most text and attribute values contain nothing to escape — the zero-allocation guard keeps those from paying the gsub copy on every render.

/[&<>\r]/
ATTRIBUTE_ESCAPABLE =
/[&<"\t\n\r]/

Instance Method Summary collapse

Instance Method Details

#encode_attribute(value) ⇒ Object

Encode attribute value Replace: & → &, < → <, " → ", #x9 → , #xA → , #xD →



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/canon/xml/character_encoder.rb', line 32

def encode_attribute(value)
  return value unless value.match?(ATTRIBUTE_ESCAPABLE)

  value.gsub(ATTRIBUTE_ESCAPABLE) do |char|
    case char
    when "&" then "&amp;"
    when "<" then "&lt;"
    when '"' then "&quot;"
    when "\t" then "&#x9;"
    when "\n" then "&#xA;"
    when "\r" then "&#xD;"
    end
  end
end

#encode_text(text) ⇒ Object

Encode text node content Replace: & → &, < → <, > → >, #xD →



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/canon/xml/character_encoder.rb', line 16

def encode_text(text)
  return text unless text.match?(TEXT_ESCAPABLE)

  text.gsub(TEXT_ESCAPABLE) do |char|
    case char
    when "&" then "&amp;"
    when "<" then "&lt;"
    when ">" then "&gt;"
    when "\r" then "&#xD;"
    end
  end
end