Module: Crystalline
- Extended by:
- T::Sig
- Defined in:
- lib/crystalline.rb,
lib/crystalline/utils.rb,
lib/crystalline/metadata_fields.rb
Overview
typed: true frozen_string_literal: true
Defined Under Namespace
Modules: MetadataFields
Class Method Summary collapse
- .non_nilable_attr_count(klass) ⇒ Object
- .to_dict(complex) ⇒ Object
- .to_json(complex) ⇒ Object
- .unmarshal_json(data, type) ⇒ Object
- .val_to_string(val, primitives: true) ⇒ Object
Class Method Details
.non_nilable_attr_count(klass) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/crystalline/utils.rb', line 58 def self.non_nilable_attr_count(klass) # somewhat sane sort ordering for Union deserialization. # All Crystalline objects return the number of non-nilable fields # All non-string primitives return 2 # All arrays and hashes return 1 # Strings return 0 (since any data can deserialize to a string, it should be our last attempt) if klass.respond_to? :fields return -1 * klass.fields.count do |field| !T.nilable? field.type end else if klass == String return 0 elsif klass.is_a?(T::Types::TypedArray) || klass.is_a?(T::Types::TypedHash) return 1 end return 2 end end |
.to_dict(complex) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/crystalline/utils.rb', line 12 def self.to_dict(complex) if complex.is_a? Array complex.map { |v| Crystalline.to_dict(v) } elsif complex.is_a? Hash complex.transform_values { |v| Crystalline.to_dict(v) } elsif complex.respond_to?(:class) && complex.class.include?(::Crystalline::MetadataFields) complex.to_dict else val_to_string complex, primitives: false end end |
.to_json(complex) ⇒ Object
24 25 26 |
# File 'lib/crystalline/utils.rb', line 24 def self.to_json(complex) JSON.dump(to_dict(complex)) end |
.unmarshal_json(data, type) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/crystalline/utils.rb', line 29 def self.unmarshal_json(data, type) if T.simplifiable? type type = T.simplify_type type end if type.instance_of?(Class) && type.include?(::Crystalline::MetadataFields) type.from_dict(data) elsif T.arr? type data.map { |v| Crystalline.unmarshal_json(v, T.arr_of(type)) } elsif T.hash? type data.transform_values { |v| Crystalline.unmarshal_json(v, T.hash_of(type)) } else data end end |
.val_to_string(val, primitives: true) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/crystalline/utils.rb', line 45 def self.val_to_string(val, primitives: true) if val.is_a? T::Enum val.serialize elsif val.is_a? DateTime val.strftime('%Y-%m-%dT%H:%M:%S.%NZ') elsif primitives val.to_s else val end end |