Class: Rollbar::Encoding::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/rollbar/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'.freeze
BINARY =
'binary'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Encoder



13
14
15
# File 'lib/rollbar/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/rollbar/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
33
34
35
36
37
38
# File 'lib/rollbar/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),
                      # Ruby 2.7 requires this to look like keyword args,
                      # and Ruby 1.9.3 doesn't understand keyword args, so
                      # don't use hash rockets here and both will be happy.
                      invalid: :replace, undef: :replace, replace: '' # rubocop:disable Style/HashSyntax
                    )
                  end

  object.is_a?(Symbol) ? encoded_value.to_sym : encoded_value
rescue StandardError => e
  # If encoding fails for any reason, replace the string with a diagnostic error.
  "error encoding string: #{e.class}: #{e.message}"
end