Last active
October 31, 2019 09:06
-
-
Save poctek/ac4c2ce619b5f58ab66f87efa8410954 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
Dry::Validation.load_extensions(:monads) | |
module BaseTransaction | |
def self.included(base) | |
base.include Dry::Transaction | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
attr_reader :_contract | |
def schema(&block) | |
klass = Class.new(Dry::Validation::Contract) do | |
schema(&block) | |
end | |
@_contract = klass.new | |
end | |
end | |
def call_validated(input) | |
self.class._contract | |
.call(input) | |
.to_monad | |
.bind { call } | |
end | |
end | |
class TestClass | |
include BaseTransaction | |
schema do | |
required(:field).filled(:str?) | |
required(:another_field).filled(:int?) | |
end | |
step :first_step | |
tee :second_step | |
private | |
def first_step(input) | |
Success(input) | |
end | |
def second_step(input) | |
nil | |
end | |
end | |
a = TestClass.new | |
a.call_validated(field: 1, another_field: 'test') | |
# => Failure(#<Dry::Validation::Result{:field=>1, :another_field=>"test"} errors={:field=>["must be a string"], :another_field=>["must be an integer"]}>) | |
a.call_validated(field: 'test', another_field: 1) | |
# => Success(nil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment