Sha256: 0fa0c9f2cb56dbd68b9286a46f53bf831d55d8212d053f51840bb34d648a9c16

Contents?: true

Size: 1.65 KB

Versions: 2

Compression:

Stored size: 1.65 KB

Contents

module Protobuf
  module Field
    class FieldArray < Array
      ##
      # Constructor
      #
      def initialize(field)
        @field = field
      end

      ##
      # Public Instance Methods
      #
      def []=(nth, val)
        super(nth, normalize(val)) unless val.nil?
      end

      def <<(val)
        super(normalize(val)) unless val.nil?
      end

      def push(val)
        super(normalize(val)) unless val.nil?
      end

      def unshift(val)
        super(normalize(val)) unless val.nil?
      end

      def replace(val)
        raise_type_error(val) unless val.is_a?(Array)
        val = val.map! { |v| normalize(v) }
        super(val)
      end

      # Return a hash-representation of the given values for this field type.
      # The value in this case would be an array.
      def to_hash_value
        self.map do |value|
          value.respond_to?(:to_hash_value) ? value.to_hash_value : value
        end
      end

      def to_s
        "[#{@field.name}]"
      end

      private

      ##
      # Private Instance Methods
      #
      def normalize(value)
        raise TypeError unless @field.acceptable?(value)

        if @field.is_a?(::Protobuf::Field::EnumField)
          @field.type.fetch(value)
        elsif @field.is_a?(::Protobuf::Field::MessageField) && value.respond_to?(:to_hash)
          @field.type.new(value.to_hash)
        else
          value
        end
      end

      def raise_type_error(val)
        error_text = <<-TYPE_ERROR
          Expected value of type '#{@field.type}'
          Got '#{val.class}' for protobuf field #{@field.name}
        TYPE_ERROR

        raise TypeError, error_text
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
protobuf-2.4.4-java lib/protobuf/field/field_array.rb
protobuf-2.4.4 lib/protobuf/field/field_array.rb