module Translatomatic::StringEscaping
String escaping/unescaping code from syck/encoding.rb
Constants
- ESCAPES
- UNESCAPES
Public Class Methods
escape(value, include = '"')
click to toggle source
Escape unprintable characters such as newlines. @param value [String] The string to escape @param include [String] Extra characters to escape @return [String] The string with special characters escaped.
# 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)
click to toggle source
Unescape character escapes such as ānā to their character equivalents. @param value [String] The string to unescape @return [String] The string with special characters unescaped.
# 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)
click to toggle source
Unescape as above, and also convert all occurrences of $char to $char @param value [String] The string to unescape @return [String] The string with all characters unescaped.
# 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