|
1 | 1 | # frozen_string_literal: true |
2 | 2 | # typed: true |
3 | 3 |
|
4 | | -require "bigdecimal" |
5 | | - |
6 | 4 | module Stripe |
7 | 5 | # For internal use only. Does not provide a stable API and may be broken |
8 | 6 | # with future non-major changes. |
@@ -64,61 +62,8 @@ def self.field_encodings |
64 | 62 | @field_encodings ||= {} |
65 | 63 | end |
66 | 64 |
|
67 | | - # Recursively coerce a value based on its field encoding schema. |
68 | | - # Handles :int64_string leaves, { kind: :object, fields: ... } nesting, |
69 | | - # and { kind: :array, element: ... } for arrays. |
70 | 65 | def self.coerce_value(value, encoding) |
71 | | - return value if value.nil? |
72 | | - |
73 | | - case encoding |
74 | | - when :int64_string |
75 | | - coerce_int64_string(value) |
76 | | - when :decimal_string |
77 | | - coerce_decimal_string(value) |
78 | | - when Hash |
79 | | - coerce_composite(value, encoding) |
80 | | - else |
81 | | - value |
82 | | - end |
83 | | - end |
84 | | - |
85 | | - private_class_method def self.coerce_int64_string(value) |
86 | | - case value |
87 | | - when Integer then value.to_s |
88 | | - when Array then value.map { |v| v.is_a?(Integer) ? v.to_s : v } |
89 | | - else value |
90 | | - end |
91 | | - end |
92 | | - |
93 | | - private_class_method def self.coerce_decimal_string(value) |
94 | | - case value |
95 | | - when BigDecimal then value.to_s("F") |
96 | | - when Integer, Float then value.to_s |
97 | | - when Array then value.map { |v| coerce_decimal_string(v) } |
98 | | - else value |
99 | | - end |
100 | | - end |
101 | | - |
102 | | - private_class_method def self.coerce_composite(value, encoding) |
103 | | - case encoding[:kind] |
104 | | - when :object |
105 | | - coerce_object(value, encoding[:fields] || {}) |
106 | | - when :array |
107 | | - return value unless value.is_a?(Array) |
108 | | - |
109 | | - value.map { |v| coerce_value(v, encoding[:element]) } |
110 | | - else |
111 | | - value |
112 | | - end |
113 | | - end |
114 | | - |
115 | | - private_class_method def self.coerce_object(value, fields_schema) |
116 | | - return value unless value.is_a?(Hash) |
117 | | - |
118 | | - value.each_with_object({}) do |(k, v), result| |
119 | | - field_encoding = fields_schema[k.to_sym] |
120 | | - result[k] = field_encoding ? coerce_value(v, field_encoding) : v |
121 | | - end |
| 66 | + V2TypeCoercion.coerce_value(value, encoding, direction: :encode) |
122 | 67 | end |
123 | 68 |
|
124 | 69 | # Coerce a plain Hash using this class's field_encodings. |
|
0 commit comments