class Bugno::Encoding::Encoder

Constants

ALL_ENCODINGS
ASCII_ENCODINGS
BINARY
ENCODING_OPTIONS
UTF8

Attributes

object[RW]

Public Class Methods

new(object) click to toggle source
# File lib/bugno/encoding/encoder.rb, line 14
def initialize(object)
  @object = object
end

Public Instance Methods

encode() click to toggle source
# File lib/bugno/encoding/encoder.rb, line 18
def encode
  value = object.to_s
  encoding = value.encoding

  # This will be most of cases so avoid force anything for them
  encoded_value = if encoding == ::Encoding::UTF_8 && value.valid_encoding?
                    value
                  else
                    force_encoding(value).encode(*encoding_args(value))
                  end

  object.is_a?(Symbol) ? encoded_value.to_sym : encoded_value
end

Private Instance Methods

detect_encoding(v) click to toggle source
# File lib/bugno/encoding/encoder.rb, line 42
def detect_encoding(v)
  value = v.dup

  ALL_ENCODINGS.detect do |encoding|
    begin
      # Seems #codepoints is faster than #valid_encoding?
      value.force_encoding(encoding).encode(::Encoding::UTF_8).codepoints
      true
    rescue StandardError
      false
    end
  end
end
encoding_args(value) click to toggle source
# File lib/bugno/encoding/encoder.rb, line 56
def encoding_args(value)
  args = [UTF8]
  args << BINARY if ASCII_ENCODINGS.include?(value.encoding)
  args << ENCODING_OPTIONS

  args
end
force_encoding(value) click to toggle source
# File lib/bugno/encoding/encoder.rb, line 34
def force_encoding(value)
  return value if value.frozen?

  value.force_encoding(detect_encoding(value)) if value.encoding == ::Encoding::UTF_8

  value
end