Class: Dommy::TextDecoder

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/text_codec.rb

Overview

‘TextDecoder` — decodes bytes into a String. Supports utf-8, utf-16, utf-16le, utf-16be, iso-8859-1 (best-effort).

Spec: encoding.spec.whatwg.org/#textdecoder

Instance Method Summary collapse

Constructor Details

#initialize(label = "utf-8", _options = nil) ⇒ TextDecoder

Returns a new instance of TextDecoder.



37
38
39
# File 'lib/dommy/text_codec.rb', line 37

def initialize(label = "utf-8", _options = nil)
  @encoding = normalize_encoding(label.to_s)
end

Instance Method Details

#__js_call__(method, args) ⇒ Object



66
67
68
69
70
71
# File 'lib/dommy/text_codec.rb', line 66

def __js_call__(method, args)
  case method
  when "decode"
    decode(args[0], args[1])
  end
end

#__js_get__(key) ⇒ Object



62
63
64
# File 'lib/dommy/text_codec.rb', line 62

def __js_get__(key)
  key == "encoding" ? encoding : nil
end

#decode(input = nil, _options = nil) ⇒ Object

decode(bytes) → String. Accepts Array<Integer> (byte values), a binary String, or anything responding to to_a/bytes.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dommy/text_codec.rb', line 47

def decode(input = nil, _options = nil)
  return "" if input.nil?

  bytes = case input
  when String
    input.b
  when Array
    input.pack("C*")
  else
    input.respond_to?(:to_a) ? input.to_a.pack("C*") : input.to_s
  end

  bytes.force_encoding(ruby_encoding).encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
end

#encodingObject



41
42
43
# File 'lib/dommy/text_codec.rb', line 41

def encoding
  @encoding
end