Class: Protobuf::Field::StringField

Inherits:
BytesField show all
Defined in:
lib/protobuf/field/string_field.rb

Constant Summary collapse

ENCODING =

Constants

Encoding::UTF_8

Constants inherited from BytesField

BytesField::BYTES_ENCODING

Constants inherited from BaseField

BaseField::OBJECT_MODULE, BaseField::PACKED_TYPES

Instance Attribute Summary

Attributes inherited from BaseField

#default_value, #fully_qualified_name, #message_class, #name, #options, #rule, #tag, #type_class

Instance Method Summary collapse

Methods inherited from BytesField

default, #wire_type

Methods inherited from BaseField

default, #default, #define_encode_to_stream!, #define_field_and_present_predicate!, #define_field_predicate!, #define_set_field!, #define_set_method!, #define_to_message_hash!, #define_value_from_values!, #define_value_from_values_for_serialization!, #deprecated?, #encode_to_stream, #enum?, #extension?, #field?, #field_and_present?, #fully_qualified_name_only!, #initialize, #map?, #message?, #optional?, #packed?, #repeated?, #repeated_message?, #required?, #set, #set_default_value!, #set_field, #set_map!, #set_repeated_message!, #tag_encoded, #to_message_hash, #to_message_hash_with_string_key, #to_s, #value_from_values, #value_from_values_for_serialization, #wire_type

Methods included from Logging

initialize_logger, #log_exception, #log_signature, #logger, #sign_message

Constructor Details

This class inherits a constructor from Protobuf::Field::BaseField

Instance Method Details

#acceptable?(val) ⇒ Boolean

Public Instance Methods

Returns:

  • (Boolean)


17
18
19
# File 'lib/protobuf/field/string_field.rb', line 17

def acceptable?(val)
  val.is_a?(String) || val.nil? || val.is_a?(Symbol)
end

#coerce!(value) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/protobuf/field/string_field.rb', line 21

def coerce!(value)
  if value.nil?
    nil
  elsif acceptable?(value)
    value.to_s
  else
    fail TypeError, "Unacceptable value #{value} for field #{name} of type #{type_class}"
  end
end

#decode(bytes) ⇒ Object



31
32
33
34
# File 'lib/protobuf/field/string_field.rb', line 31

def decode(bytes)
  bytes.force_encoding(::Protobuf::Field::StringField::ENCODING)
  bytes
end

#encode(value) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/protobuf/field/string_field.rb', line 36

def encode(value)
  value_to_encode = "" + value # dup is slower
  unless value_to_encode.encoding == ENCODING
    value_to_encode.encode!(::Protobuf::Field::StringField::ENCODING, :invalid => :replace, :undef => :replace, :replace => "")
  end
  value_to_encode.force_encoding(::Protobuf::Field::BytesField::BYTES_ENCODING)

  "#{::Protobuf::Field::VarintField.encode(value_to_encode.bytesize)}#{value_to_encode}"
end

#json_encode(value, options = {}) ⇒ Object



46
47
48
# File 'lib/protobuf/field/string_field.rb', line 46

def json_encode(value, options={})
  value
end