Module: Translatomatic::StringEscaping

Defined in:
lib/translatomatic/string_escaping.rb

Overview

String escaping/unescaping code from syck/encoding.rb

Class Method Summary collapse

Class Method Details

.escape(value, include = '"') ⇒ String

Escape unprintable characters such as newlines.

Parameters:

  • value (String)

    The string to escape

  • include (String) (defaults to: '"')

    Extra characters to escape

Returns:

  • (String)

    The string with special characters escaped.



23
24
25
26
27
28
29
30
31
32
# File 'lib/translatomatic/string_escaping.rb', line 23

def escape(value, include = '"')
  return nil if value.nil?
  new_value = value.dup
  new_value.gsub!(/\\/, '\\\\\\')
  if include.present?
    new_value.gsub!(/([#{include}])/) { '\\' + Regexp.last_match(1) }
  end
  new_value.gsub!(/([\x00-\x1f])/) { ESCAPES[ $&.unpack('C')[0] ] }
  new_value
end

.unescape(value) ⇒ String

Unescape character escapes such as “n” to their character equivalents.

Parameters:

  • value (String)

    The string to unescape

Returns:

  • (String)

    The string with special characters unescaped.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/translatomatic/string_escaping.rb', line 37

def unescape(value)
  return nil if value.nil?
  regex = /\\(?:([nevfbart\\])|0?x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/
  value.gsub(regex) do
    if Regexp.last_match(3)
      [Regexp.last_match(3).to_s.hex].pack('U*')
    elsif Regexp.last_match(2)
      [Regexp.last_match(2)].pack('H2')
    else
      UNESCAPES[Regexp.last_match(1)]
    end
  end
end

.unescape_all(value) ⇒ String

Unescape as above, and also convert all occurrences of $char to $char

Parameters:

  • value (String)

    The string to unescape

Returns:

  • (String)

    The string with all characters unescaped.



54
55
56
57
58
# File 'lib/translatomatic/string_escaping.rb', line 54

def unescape_all(value)
  return nil if value.nil?
  value = unescape(value).gsub(/\\(.)/) { Regexp.last_match(1) }
  value
end