Module: Pb::Serializable

Extended by:
ActiveSupport::Concern, ClassMethods, Dsl
Includes:
ComputedModel::Model
Included in:
Pb::Serializer::Base
Defined in:
lib/pb/serializable.rb,
lib/pb/serializable/dsl.rb,
lib/pb/serializable/dsl/oneof.rb,
lib/pb/serializable/dsl/attribute.rb,
lib/pb/serializable/computed_model_support.rb

Defined Under Namespace

Modules: ClassMethods, Dsl

Instance Method Summary collapse

Methods included from Dsl

attribute, ignore, message, oneof

Methods included from ClassMethods

bulk_load, bulk_load_and_serialize

Instance Method Details

#to_pb(with: nil) ⇒ Object

Returns a protobuf message object.

Parameters:

  • with (Google::Protobuf::FieldMask, Array<(Symbol, Hash)>, Hash{Symbol=>(Array,Symbol,Hash,Proc)}, ) (defaults to: nil)

    Specifies the list of fields to be serialized in the Proto message object. ‘nil` means that all fields defined in .proto will be serialized.

Returns:

  • (Object)

    a protobuf message object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/pb/serializable.rb', line 25

def to_pb(with: nil)
  with ||= ::Pb::Serializer.build_default_mask(self.class.__pb_serializer_message_class.descriptor)
  with = ::Pb::Serializer.normalize_mask(with)

  oneof_set = []

  o = self.class.__pb_serializer_message_class.new
  self.class.__pb_serializer_message_class.descriptor.each do |fd|
    attr = self.class.__pb_serializer_attr_by_field_descriptor(fd)

    unless attr
      msg = "#{self.class.__pb_serializer_message_class.name}.#{fd.name} is missed in #{self.class.name}"

      case Pb::Serializer.configuration.missing_field_behavior
      when :raise then raise ::Pb::Serializer::MissingFieldError, msg
      when :warn  then Pb::Serializer.logger.warn msg
      end

      next
    end

    next unless with.key?(attr.name)
    next unless attr.serializable?(self)

    raise "#{self.name}.#{attr.name} is not defined" unless respond_to?(attr.name)

    v = public_send(attr.name)
    v = attr.convert_to_pb(v, with: with[attr.name])

    if attr.oneof?
      if !v.nil?
        if oneof_set.include?(attr.oneof)
          raise ::Pb::Serializer::ConflictOneofError, "#{primary_object.class.name}##{attr.name} is oneof attribute"
        end
        oneof_set << attr.oneof
      end
    elsif !attr.allow_nil? && v.nil?
      raise ::Pb::Serializer::ValidationError, "#{primary_object.class.name}##{attr.name} is required"
    end

    next if v.nil?

    if attr.repeated?
      o.public_send(attr.name).push(*v)
    else
      o.public_send("#{attr.name}=", v)
    end
  end

  self.class.__pb_serializer_oneof_by_name.values.each do |oneof|
    next if oneof_set.include?(oneof.name)
    next if oneof.allow_nil?
    raise ::Pb::Serializer::ValidationError, "#{primary_object.class.name}##{oneof.name} is required"
  end

  o
end