Module: Dry::Transaction::Extra::ValidationDSL
- Defined in:
- lib/dry/transaction/extra/validation_dsl.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#validate(contract = nil, &block) ⇒ Object
Allows you to declare a class-level validator, and run it as the first step of the Transaction.
Class Method Details
.extended(klass) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/dry/transaction/extra/validation_dsl.rb', line 7 def self.extended(klass) klass.extend Dry::Core::ClassAttributes # The Dry::Validation Contract to run as the first step in the # Transaction. This exposes it publicly, so you can run it outside # the context of the Transction. This is useful if, for example, you # want to run the transaction in a job, but want to check if the # arguments are valid before enqueueing the job. # # @example # # class MyTransaction # validate do # params do # required(:name).filled(:string) # end # end # end # # MyTransaction.validator.new.call(name: "Jane") # # => #<Dry::Validation::Result{name: "Jane"} errors={}> klass.defines :validator require "dry/validation" Dry::Validation.load_extensions(:monads) end |
Instance Method Details
#validate(contract = nil, &block) ⇒ Object
Allows you to declare a class-level validator, and run it as the first step of the Transaction.
class CreateUser
include Dry::Transaction
include Dry::Transaction::Extra
load_extensions :validation
validate do
params do
required(:name).filled(:string)
optional(:email).maybe(:string)
end
end
end
class NewUserContract < Dry::Validation::Contract
params do
required(:name).filled(:string)
optional(:email).maybe(:string)
end
end
class CreateUser
include Dry::Transaction
include Dry::Transaction::Extra
load_extensions :validation
validate NewUserContract
end
68 69 70 71 72 |
# File 'lib/dry/transaction/extra/validation_dsl.rb', line 68 def validate(contract = nil, &block) validator(contract || Class.new(Dry::Validation::Contract, &block)) valid(validator.new, name: "validate") end |