Class: Deimos::AvroSchemaCoercer
- Inherits:
-
Object
- Object
- Deimos::AvroSchemaCoercer
- Defined in:
- lib/deimos/schema_backends/avro_schema_coercer.rb
Overview
Class to coerce values in a payload to match a schema.
Instance Method Summary collapse
- #coerce_type(type, val) ⇒ Object
-
#initialize(schema) ⇒ AvroSchemaCoercer
constructor
A new instance of AvroSchemaCoercer.
Constructor Details
#initialize(schema) ⇒ AvroSchemaCoercer
Returns a new instance of AvroSchemaCoercer.
9 10 11 |
# File 'lib/deimos/schema_backends/avro_schema_coercer.rb', line 9 def initialize(schema) @schema = schema end |
Instance Method Details
#coerce_type(type, val) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/deimos/schema_backends/avro_schema_coercer.rb', line 16 def coerce_type(type, val) int_classes = [Time, ActiveSupport::TimeWithZone] field_type = type.type.to_sym if field_type == :union union_types = type.schemas.map { |s| s.type.to_sym } return nil if val.nil? && union_types.include?(:null) field_type = union_types.find { |t| t != :null } end case field_type when :int, :long if val.is_a?(Integer) || _is_integer_string?(val) || int_classes.any? { |klass| val.is_a?(klass) } val.to_i else val # this will fail end when :float, :double if val.is_a?(Numeric) || _is_float_string?(val) val.to_f else val # this will fail end when :string if val.respond_to?(:to_str) val.to_s elsif _is_to_s_defined?(val) val.to_s else val # this will fail end when :boolean if val.nil? || val == false false else true end else val end end |