Module: Paramore::CastParameters
- Defined in:
- lib/paramore/cast_parameters.rb
Class Method Summary collapse
- .cast(field, value, name = nil) ⇒ Object
- .missing_and_optional?(hash, name, field) ⇒ Boolean
- .run(field, data) ⇒ Object
- .typecast_array(field, array, name) ⇒ Object
- .typecast_hash(field, hash, name) ⇒ Object
- .typecast_value(type, value, name) ⇒ Object
Class Method Details
.cast(field, value, name = nil) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/paramore/cast_parameters.rb', line 10 def cast(field, value, name = nil) if value.nil? if field.nullable? || field.default? return field.default else raise Paramore::NilParameter, name end end case field.type when Hash typecast_hash(field, value || {}, name) when Array typecast_array(field, value, name) else if value == '' && !field.allow_empty? && field.nullable? nil else typecast_value(field.type, value, name) end end end |
.missing_and_optional?(hash, name, field) ⇒ Boolean
68 69 70 |
# File 'lib/paramore/cast_parameters.rb', line 68 def missing_and_optional?(hash, name, field) !hash.key?(name) && !field.required? end |
.run(field, data) ⇒ Object
6 7 8 |
# File 'lib/paramore/cast_parameters.rb', line 6 def run(field, data) cast(field, data, 'data') end |
.typecast_array(field, array, name) ⇒ Object
54 55 56 57 58 59 60 61 62 |
# File 'lib/paramore/cast_parameters.rb', line 54 def typecast_array(field, array, name) raise Paramore::ArrayExpected.new(name, array) unless array.is_a?(Array) result = array .reject { |unit| unit.to_s == '' && field.compact? } .map { |unit| cast(Paramore.field(field.type.first, null: true), unit) } field.compact? ? result.compact : result end |
.typecast_hash(field, hash, name) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/paramore/cast_parameters.rb', line 33 def typecast_hash(field, hash, name) raise Paramore::HashExpected.new(name, hash) unless hash.is_a?(Hash) result = if field.wildly_keyed_hash? value_field = field.type.values.first key_type = field.type.keys.first hash.to_h do |name, value| [typecast_value(key_type, name, nil), cast(value_field, value, name)] end else field .type .reject { |name, value_field| missing_and_optional?(hash, name, value_field) } .to_h { |name, value_field| [name, cast(value_field, hash[name], name)] } end field.compact? ? result.compact : result end |
.typecast_value(type, value, name) ⇒ Object
64 65 66 |
# File 'lib/paramore/cast_parameters.rb', line 64 def typecast_value(type, value, name) type.send(Paramore.configuration.type_method_name, value) end |