Validating params or attributes
First of all, thanks for the great work! 💯
In interactor with the interactor-contracts gem, it's possible to validate a hash like this:
expects do
required(:user).filled(type?: User)
required(:params).schema do
required(:email).filled(:str?)
required(:first_name).filled(:str?)
optional(:middle_name)
end
end
Is there a similar way? Or a recommended way of achieving the same thing?
Hi @lifelofranco!
Good call. There’s no such way to validate keys inside hashes with the current validation system.
One way you could do this out of the box would be using must. E.g.:
class CreateUser
input :user, type: User
input :params,
must: {
have_email: -> h { h[:email].present? },
have_first_name: -> h { h[:first_name].present? },
}
In the future perhaps we could build another validator for hashes that could perhaps look like this:
class CreateUser
input :user, type: User
input :params,
hash: -> do
input :email
input :first_name
input :middle_name, optional: true
end
Edit: Fixed syntax for -> h
Another option would be to add support for contracts like the interactor-contract gem does.
Is there any of these solutions you would like to try and implement @lifelofranco?
I think there is a typo in the current example (h -> vs -> h).
class CreateUser
input :user, type: User
input :params,
must: {
have_email: -> (h) { h[:email].present? },
have_first_name: -> (h) { h[:first_name].present? },
}
@pboling Good call! I’ve fixed the comment 👍🏻