Sha256: 7fe8de663735850225f7c6ed5772fc04482bb5476d443a28013d7153a987521d

Contents?: true

Size: 1.52 KB

Versions: 24

Compression:

Stored size: 1.52 KB

Contents

require 'protobuf/field/base_field'

module Protobuf
  module Field
    class MessageField < BaseField

      ##
      # Public Instance Methods
      #

      def acceptable?(val)
        unless val.instance_of?(type_class) || val.respond_to?(:to_hash)
          raise TypeError, "Expected value of type '#{type_class}' for field #{name}, but got '#{val.class}'"
        end

        true
      end

      def decode(bytes)
        type_class.decode(bytes)
      end

      def encode(value)
        bytes = value.encode
        result = ::Protobuf::Field::VarintField.encode(bytes.size)
        result << bytes
      end

      def message?
        true
      end

      def wire_type
        ::Protobuf::WireType::LENGTH_DELIMITED
      end

      private

      ##
      # Private Instance Methods
      #

      def define_setter
        field = self
        message_class.class_eval do
          define_method("#{field.name}=") do |val|
            case
            when val.nil? then
              @values.delete(field.name)
            when val.is_a?(field.type_class) then
              @values[field.name] = val
            when val.respond_to?(:to_proto) then
              @values[field.name] = val.to_proto
            when val.respond_to?(:to_hash) then
              @values[field.name] = field.type_class.new(val.to_hash)
            else
              raise TypeError, "Expected value of type '#{field.type_class}' for field #{field.name}, but got '#{val.class}'"
            end
          end
        end
      end

    end
  end
end

Version data entries

24 entries across 24 versions & 2 rubygems

Version Path
protobuffy-3.6.0 lib/protobuf/field/message_field.rb
protobuffy-3.5.1 lib/protobuf/field/message_field.rb
protobuffy-3.4.0 lib/protobuf/field/message_field.rb
protobuffy-3.3.0 lib/protobuf/field/message_field.rb
protobuffy-3.2.0 lib/protobuf/field/message_field.rb
protobuffy-3.1.0 lib/protobuf/field/message_field.rb
protobuf-3.3.6 lib/protobuf/field/message_field.rb
protobuf-3.3.5 lib/protobuf/field/message_field.rb
protobuf-3.3.4 lib/protobuf/field/message_field.rb
protobuf-3.3.3 lib/protobuf/field/message_field.rb
protobuf-3.3.2 lib/protobuf/field/message_field.rb
protobuf-3.3.1 lib/protobuf/field/message_field.rb
protobuf-3.3.0 lib/protobuf/field/message_field.rb
protobuf-3.2.1 lib/protobuf/field/message_field.rb
protobuf-3.2.0 lib/protobuf/field/message_field.rb
protobuf-3.1.0 lib/protobuf/field/message_field.rb
protobuf-3.0.5 lib/protobuf/field/message_field.rb
protobuf-3.0.4 lib/protobuf/field/message_field.rb
protobuf-3.0.3 lib/protobuf/field/message_field.rb
protobuf-3.0.2 lib/protobuf/field/message_field.rb