class KRPC::Types::TypeStore
Public Class Methods
[](protobuf_type)
click to toggle source
# 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)
click to toggle source
# 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