Project

broi-input

0.0
No commit activity in last 3 years
No release in over 3 years
Destructures incoming user input onto dry struct
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.16
>= 0
~> 0.11
~> 10.0
~> 3.0

Runtime

 Project Readme

Broi::Input

This library provides flexible API to deal with incoming ruby messages. It converts incoming hash onto predefined, structured object by passing it through predefined input validations.

Example:

class PurchaseInput < Broi::Input
  attribute :product
  attribute :count, default: 1
  
  validate do
    required(:product).filled(:str?)
    optional(:count).maybe(:int?) 
  end
end

###Processing incoming hash

You instantiate the input by executing call method which, depending on the validation resutls, returns an instance of Broi::Input::Success/Failure.

PurchaseInput.(product: 'Apple')
#=> #Success(<#PurchaseInput|soft product=#Value('Apple')>)


PurchaseInput.(product: 123)
#=> Failure({:product => ["must be string"])

Soft input struct

Regardless of the validation result, you can always obtain soft input result by calling input on the result:

PurchaseInput.(product: 'Apple').input
#=> <#PurchaseInput|soft product=#Value('Apple')>

PurchaseInput.(product: 123).input
#=> <#PurchaseInput|soft product=#InvalidValue(123)>

All the values accessible through the soft input are either Broi::Input::Value/InvalidValue and they respond to valid? and invalid? methods.

Strict input

You can turn soft input into a strict input by calling valid!. Strict input is just typical Dry::Struct:

PurchaseInput.(product: 'Apple').input.valid!
#=> <#PurchaseInput product='Apple'>

PurchaseInput.(product: 123).input.valid!
#! raises: Broi::Input::Invalid 

Validation errors

Errors can be collected directly from the processing result.

PurchaseInput.(product: 'Apple').errors
#=> {}

PurchaseInput.(product: 123).errors
#=> {:product => ["must be string"])