Class: Translatomatic::EscapedUnicode

Inherits:
Object
  • Object
show all
Defined in:
lib/translatomatic/escaped_unicode.rb

Overview

Class to encode and decode unicode chars. This code is highly influenced by Florian Frank’s JSON gem

Class Method Summary collapse

Class Method Details

.escape(text) ⇒ String

Decodes all unicode chars into escape sequences

Parameters:

  • text (String)

Returns:

  • (String)

    The decoded text



22
23
24
25
26
27
28
29
# File 'lib/translatomatic/escaped_unicode.rb', line 22

def escape(text)
  string = text.dup
  string.force_encoding(::Encoding::ASCII_8BIT)
  string.gsub!(/["\\\x0-\x1f]/n) { |c| MAP[c] || c }
  string.gsub!(ESCAPE_REGEX) { |c| escape_char(c) }
  string.force_encoding(::Encoding::UTF_8)
  string
end

.unescape(text) ⇒ String

Decodes all unicode chars from escape sequences

Parameters:

  • text (String)

Returns:

  • (String)

    The encoded text



11
12
13
14
15
16
17
# File 'lib/translatomatic/escaped_unicode.rb', line 11

def unescape(text)
  string = text.gsub(/(?:\\[uU](?:[A-Fa-f\d]{4}))+/) do |c|
    unescape_char(c)
  end
  string.force_encoding(::Encoding::UTF_8)
  string
end