Class: SmartParams::Field
- Inherits:
-
Object
- Object
- SmartParams::Field
- Defined in:
- lib/smart_params/field.rb
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
Instance Method Summary collapse
-
#initialize(path:, type:, optional: false) ⇒ Field
constructor
A new instance of Field.
- #map(raw) ⇒ Object
- #update_in(result, value) ⇒ Object
Constructor Details
#initialize(path:, type:, optional: false) ⇒ Field
Returns a new instance of Field.
8 9 10 11 12 |
# File 'lib/smart_params/field.rb', line 8 def initialize(path:, type:, optional: false, **) @path = path @type = type @optional = !!optional end |
Instance Attribute Details
#path ⇒ Object (readonly)
Returns the value of attribute path.
5 6 7 |
# File 'lib/smart_params/field.rb', line 5 def path @path end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
6 7 8 |
# File 'lib/smart_params/field.rb', line 6 def type @type end |
Instance Method Details
#map(raw) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/smart_params/field.rb', line 14 def map(raw) case [*dig_until(@path, raw), @type, @type&.optional? || @optional] in [:error, last, _, false] [:error, SmartParams::MissingPropertyException.new(path:, last:)] in [:error, _, _, true] :skip in [:ok, value, nil, _] [:ok, value] in [:ok, value, type, _] type.try(value) end rescue Dry::Types::ConstraintError => constraint_error Dry::Types::Result::Failure.new(value, constraint_error) end |
#update_in(result, value) ⇒ Object
29 30 31 32 33 34 35 36 37 |
# File 'lib/smart_params/field.rb', line 29 def update_in(result, value) *body, butt = @path result.dup.tap do |tree| body.reduce(tree) do |mapping, key| mapping[key] end.store(butt, value) end end |