Class: KRPC::Types::TypeStore

Inherits:
Object
  • Object
show all
Defined in:
lib/krpc/types.rb

Class Method Summary collapse

Class Method Details

.[](protobuf_type) ⇒ Object



33
34
35
# File 'lib/krpc/types.rb', line 33

def [](protobuf_type)
  @cache[protobuf_type.to_proto.hash] ||= PROTOBUF_TYPE_CODE_TO_TYPE_TYPE[protobuf_type.code].new(protobuf_type)
end

.coerce_to(value, type) ⇒ Object

Raises:



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
# File 'lib/krpc/types.rb', line 37

def coerce_to(value, type)
  return value if type.is_a?(EnumType) && value.class == Symbol # Enum handling
  return value if value.is_a?(type.ruby_type)
  # A NilClass can be coerced to a ClassType
  return nil if type.is_a?(ClassType) && value.nil?
  # Handle service' class instance
  if type.is_a?(ClassType) && value.is_a?(Gen::ClassBase) &&
     type.ruby_type == value.class
    return value
  end
  # -- Collection types --
  begin
    # coerce "list" to array
    if type.is_a?(ListType) && value.respond_to?(:map) && value.respond_to?(:to_a)
      return type.ruby_type.new(value.map{|x| coerce_to(x, type.value_type) }.to_a)
    end
    # coerce "tuple" to array + check elements count
    if type.is_a?(TupleType) && value.respond_to?(:map) && value.respond_to?(:to_a) && value.respond_to?(:size)
      raise ValueError if value.size != type.value_types.size
      return type.ruby_type.new(value.map.with_index{|x,i| coerce_to(x, type.value_types[i]) }.to_a)
    end
  rescue ValueError
    raise(ValueError, "Failed to coerce value #{value.to_s} of type #{value.class} to type #{type}")
  end
  # Numeric types
  if type.ruby_type == Float && ( value.kind_of?(Float) || value.to_s.numeric? )
    return value.to_f
  elsif type.ruby_type == Integer && ( value.kind_of?(Integer) || value.to_s.integer? )
    return value.to_i
  end
  # Convert value type to string
  if type.ruby_type == String
    return value.to_s
  end
  raise(ValueError, "Failed to coerce value #{value.to_s} of type #{value.class} to type #{type}")
end