Class: ProtocolBuffers::Field::StringField

Inherits:
BytesField show all
Defined in:
lib/protocol_buffers/runtime/field.rb

Instance Attribute Summary

Attributes inherited from ProtocolBuffers::Field

#name, #otype, #tag

Instance Method Summary collapse

Methods inherited from BytesField

#default_value, #valid_type?

Methods included from WireFormats::LENGTH_DELIMITED

#wire_type

Methods inherited from ProtocolBuffers::Field

#add_methods_to, #check_valid, #check_value, create, #initialize, #inspect_value, #repeated?, #serialize, #valid_type?

Constructor Details

This class inherits a constructor from ProtocolBuffers::Field

Instance Method Details

#deserialize(value) ⇒ Object

TODO: UTF-8 validation Make sure to handle this weird case: strings are mutable, so a UTF-8 valid string could be assigned to a repeated field and then modified in place later on to not be valid UTF-8 anymore.

Maybe we just punt on this except in Ruby 1.9 where we can rely on the language ensuring the string is always UTF-8?



267
268
269
270
271
272
273
274
275
276
277
# File 'lib/protocol_buffers/runtime/field.rb', line 267

def deserialize(value)
  # To get bytes, the value was being read as ASCII.  Ruby 1.9 stores an encoding
  # with its strings, and they were getting returned with Encoding ASCII-8BIT.
  # Protobuffers are supposed to only return UTF-8 strings.  This attempts to
  # force the encoding to UTF-8 if on Ruby 1.9 (force_encoding is defined on String).
  read_value = value.read.to_s
  if read_value.respond_to?("force_encoding")
    read_value.force_encoding("UTF-8")
  end
  read_value
end