Class: Dommy::TextEncoder

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

Overview

‘TextEncoder` — encodes a String into UTF-8 bytes. Per spec, only “utf-8” encoding is supported.

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

Instance Method Summary collapse

Methods included from Bridge::Methods

included

Instance Method Details

#__js_call__(method, args) ⇒ Object



27
28
29
30
31
32
# File 'lib/dommy/text_codec.rb', line 27

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

#__js_get__(key) ⇒ Object



21
22
23
# File 'lib/dommy/text_codec.rb', line 21

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

#encode(input = "") ⇒ Object

encode(string) → Uint8Array (UTF-8 bytes). Lone surrogates in the input have already been replaced with U+FFFD when the JS string crossed into Ruby (Ruby strings can’t hold them), matching the spec’s USVString conversion.



16
17
18
19
# File 'lib/dommy/text_codec.rb', line 16

def encode(input = "")
  str = input.equal?(Bridge::UNDEFINED) ? "" : input.to_s
  Bridge::Bytes.new(str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace).bytes)
end

#encodingObject



9
10
11
# File 'lib/dommy/text_codec.rb', line 9

def encoding
  "utf-8"
end