Class: Methodist::Interactor
- Includes:
- Dry::Transaction
- Defined in:
- lib/methodist/interactor.rb
Overview
Methodist::Interactor
Base class for a Methodist interactor.
Methodist::Interactor dependency from dry-rb transactions and dry-rb validations
Defined Under Namespace
Classes: InputClassError, SchemaDefinitionError
Constant Summary collapse
- SCHEMA_CONST =
'SCHEMA'
Instance Attribute Summary collapse
-
#validation_result ⇒ Object
Returns the value of attribute validation_result.
Class Method Summary collapse
-
.schema(&block) ⇒ Object
Method set Dry::Validation schema for an interactor.
Instance Method Summary collapse
-
#validate(input) ⇒ Object
Method for validation input of interactor parameters.
Methods inherited from Pattern
Instance Attribute Details
#validation_result ⇒ Object
Returns the value of attribute validation_result.
14 15 16 |
# File 'lib/methodist/interactor.rb', line 14 def validation_result @validation_result end |
Class Method Details
.schema(&block) ⇒ Object
Method set Dry::Validation schema for an interactor.
Receive block for generating Dry::Validation schema result.
class InteractorClass < Methodist::Interactor
schema do
required(:name).value(:str?)
end
step :validate
end
InteractorClass.new.call(name: nil) #=> Failure(ValidationError)
See
41 42 43 44 45 46 47 |
# File 'lib/methodist/interactor.rb', line 41 def schema(&block) if block_given? const_set SCHEMA_CONST, Dry::Validation.Schema(&block) else raise SchemaDefinitionError, 'You must pass block to `schema`' end end |
Instance Method Details
#validate(input) ⇒ Object
Method for validation input of interactor parameters.
Parameters
input[Hash] - parameters for interactor
Example
# app/interactors/interactor_class.rb
class InteractorClass < Methodist::Interactor
schema do
required(:name).value(:str?)
end
step :validate
end
# your controller action
def create
result = InteractorClass.new.call(name: nil) #=> Failure(ValidationError)
raise InteractorError, result.value if result.failure?
end
Return
Dry::Monads::Result::Success- success result of interactor stepDry::Monads::Result::Failure- failure result of interactor step
Raise
SchemaDefinitionError- raise if method was called without a schema definition
Attention
You can redefine failure_validation_value for a custom value returning in case of validation Failure
85 86 87 88 89 90 91 92 93 |
# File 'lib/methodist/interactor.rb', line 85 def validate(input) input = {} unless input raise InputClassError, 'If you want to use custom #validate, you have to pass a hash to an interactor' unless input.is_a?(Hash) schema = self.class.const_get SCHEMA_CONST rescue nil raise SchemaDefinitionError, 'You have to define a schema with #schema method' unless schema @validation_result = schema.call(input) return Success(validation_result.to_h) if validation_result.success? Failure(failure_validation_value) end |