Module: UTF8Encoding::ControlCharacters

Included in:
UTF8Encoding
Defined in:
lib/ndr_support/utf8_encoding/control_characters.rb

Overview

Allows any supported object to have control characters escaped, using standard replacement scheme.

Constant Summary collapse

CONTROL_CHARACTERS =

The range of characters we consider:

/[\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f]|\x7f/

Instance Method Summary collapse

Instance Method Details

#escape_control_chars(string) ⇒ Object

Returns a copy of ‘string`, with any control characters escaped.



23
24
25
# File 'lib/ndr_support/utf8_encoding/control_characters.rb', line 23

def escape_control_chars(string)
  escape_control_chars!(string.dup)
end

#escape_control_chars!(string) ⇒ Object

Escapes in-place any control characters in ‘string`, before returning it.



28
29
30
31
32
33
# File 'lib/ndr_support/utf8_encoding/control_characters.rb', line 28

def escape_control_chars!(string)
  string.gsub!(CONTROL_CHARACTERS) do |character|
    UTF8Encoding::REPLACEMENT_SCHEME[character]
  end
  string
end

#escape_control_chars_in_array!(array) ⇒ Object

Escape control characters in elements of the given ‘array`.



41
42
43
# File 'lib/ndr_support/utf8_encoding/control_characters.rb', line 41

def escape_control_chars_in_array!(array)
  array.each { |element| escape_control_chars_in_object!(element) }
end

#escape_control_chars_in_hash!(hash) ⇒ Object

Escape control characters in values of the given ‘hash`.



36
37
38
# File 'lib/ndr_support/utf8_encoding/control_characters.rb', line 36

def escape_control_chars_in_hash!(hash)
  hash.each_value { |value| escape_control_chars_in_object!(value) }
end

#escape_control_chars_in_object!(object) ⇒ Object

Recursively escape any control characters in ‘object`.



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/ndr_support/utf8_encoding/control_characters.rb', line 9

def escape_control_chars_in_object!(object)
  case object
  when String
    escape_control_chars!(object)
  when Hash
    escape_control_chars_in_hash!(object)
  when Array
    escape_control_chars_in_array!(object)
  else
    object
  end
end