Total Complexity | 3 |
Total Lines | 47 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | # frozen_string_literal: true |
||
14 | class DateTimeType < Type |
||
15 | def initialize |
||
16 | super(DateTime) |
||
17 | |||
18 | normalizer_block do |entity, *| |
||
19 | entity.iso8601(3) |
||
20 | end |
||
21 | |||
22 | define_denormalizer |
||
23 | define_factory |
||
24 | |||
25 | enumerator_block do |*| |
||
26 | ::Enumerator.new { |*| } |
||
27 | end |
||
28 | |||
29 | injector_block { |*| } |
||
30 | end |
||
31 | |||
32 | private |
||
33 | |||
34 | def define_denormalizer |
||
35 | denormalizer_block do |input, _, ctx| |
||
36 | break input if input.is_a?(DateTime) |
||
37 | input = input.to_s if input.is_a?(Symbol) |
||
38 | break DateTime.iso8601(input, 3) if input.is_a?(String) |
||
39 | if input.is_a?(Integer) |
||
40 | break DateTime.strptime(input.to_s, '%s') |
||
41 | end |
||
42 | singleton_class.send(:include, Mixin::Errors) |
||
43 | message = 'String input expected (like ' \ |
||
44 | "'2001-02-03T04:05:06.123+04:00'), " \ |
||
45 | "#{input.class} received: #{input}" |
||
46 | mapping_error(message, context: ctx) |
||
47 | end |
||
48 | end |
||
49 | |||
50 | def define_factory |
||
51 | factory_block do |_, _, ctx| |
||
52 | singleton_class.send(:include, Mixin::Errors) |
||
53 | message = 'DateTime type could not be instantiated directly, ' \ |
||
54 | 'it only supports normalization and denormalization' |
||
55 | compliance_error(message, context: ctx) |
||
56 | end |
||
57 | end |
||
58 | |||
59 | INSTANCE = new |
||
60 | end |
||
61 | end |
||
66 |