Class: Bugno::Encoding::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/bugno/encoding/encoder.rb

Constant Summary collapse

ALL_ENCODINGS =
[::Encoding::UTF_8, ::Encoding::ISO_8859_1, ::Encoding::ASCII_8BIT, ::Encoding::US_ASCII].freeze
ASCII_ENCODINGS =
[::Encoding::US_ASCII, ::Encoding::ASCII_8BIT, ::Encoding::ISO_8859_1].freeze
UTF8 =
'UTF-8'
BINARY =
'binary'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Encoder

Returns a new instance of Encoder.



13
14
15
# File 'lib/bugno/encoding/encoder.rb', line 13

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



11
12
13
# File 'lib/bugno/encoding/encoder.rb', line 11

def object
  @object
end

Instance Method Details

#encodeObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/bugno/encoding/encoder.rb', line 17

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),
                      invalid: :replace, undef: :replace, replace: ''
                    )
                  end

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