Class: ProtocolBuffers::Field::EnumField

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

Instance Attribute Summary collapse

Attributes inherited from ProtocolBuffers::Field

#name, #otype, #tag

Instance Method Summary collapse

Methods inherited from Int32Field

#bits, #max, #min

Methods inherited from SignedVarintField

#deserialize

Methods inherited from VarintField

#valid_type?

Methods included from WireFormats::VARINT

#wire_type

Methods inherited from NumericField

#max, #min

Methods inherited from ProtocolBuffers::Field

#add_methods_to, #add_reader_to, #add_writer_to, #check_valid, create, #deserialize, #packed?, #repeated?, #serialize, #valid_type?

Constructor Details

#initialize(proxy_enum, otype, name, tag, opts = {}) ⇒ EnumField

Returns a new instance of EnumField.



586
587
588
589
590
591
592
593
# File 'lib/protocol_buffers/runtime/field.rb', line 586

def initialize(proxy_enum, otype, name, tag, opts = {})
  super(otype, name, tag, opts)
  @proxy_enum = proxy_enum
  @valid_values = @proxy_enum.constants.map { |c| @proxy_enum.const_get(c) }.sort
  @value_to_name = @proxy_enum.constants.inject({}) { |h, c|
    h[@proxy_enum.const_get(c)] = c.to_s; h
  }
end

Instance Attribute Details

#valid_valuesObject (readonly)

Returns the value of attribute valid_values.



584
585
586
# File 'lib/protocol_buffers/runtime/field.rb', line 584

def valid_values
  @valid_values
end

#value_to_nameObject (readonly)

Returns the value of attribute value_to_name.



584
585
586
# File 'lib/protocol_buffers/runtime/field.rb', line 584

def value_to_name
  @value_to_name
end

Instance Method Details

#check_value(value) ⇒ Object

Raises:

  • (ArgumentError)


595
596
597
# File 'lib/protocol_buffers/runtime/field.rb', line 595

def check_value(value)
  raise(ArgumentError, "value is out of range for #{self.class.name}: #{value}") unless @valid_values.include?(value)
end

#default_valueObject



599
600
601
# File 'lib/protocol_buffers/runtime/field.rb', line 599

def default_value
  @opts[:default] || @valid_values.first
end

#inspect_value(value) ⇒ Object



607
608
609
# File 'lib/protocol_buffers/runtime/field.rb', line 607

def inspect_value(value)
  "#{@value_to_name[value]}(#{value})"
end

#text_format(io, value, options = nil) ⇒ Object



611
612
613
614
# File 'lib/protocol_buffers/runtime/field.rb', line 611

def text_format(io, value, options = nil)
  formatted = @value_to_name[value] || value.to_s
  io.write formatted 
end

#value_from_name(name) ⇒ Object



603
604
605
# File 'lib/protocol_buffers/runtime/field.rb', line 603

def value_from_name(name)
  @proxy_enum.name_to_value_map[name.to_sym]
end