Skip to content

Instantly share code, notes, and snippets.

@poctek
Last active October 31, 2019 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poctek/ac4c2ce619b5f58ab66f87efa8410954 to your computer and use it in GitHub Desktop.
Save poctek/ac4c2ce619b5f58ab66f87efa8410954 to your computer and use it in GitHub Desktop.
# 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