Class: RequestHandler::Validation::DryEngine

Inherits:
Engine
  • Object
show all
Defined in:
lib/request_handler/validation/dry_engine.rb

Class Method Summary collapse

Class Method Details

.call_schema(value, schema, options) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/request_handler/validation/dry_engine.rb', line 22

def self.call_schema(value, schema, options)
  if options.empty?
    schema_instance?(schema) ? schema.call(value) : schema.new.call(value)
  else
    schema_instance?(schema) ? schema.with(**options).call(value) : schema.new(**options).call(value)
  end
end

.error_message(validation_error) ⇒ Object



51
52
53
# File 'lib/request_handler/validation/dry_engine.rb', line 51

def self.error_message(validation_error)
  validation_error
end

.error_pointer(_validation_error) ⇒ Object



55
56
57
# File 'lib/request_handler/validation/dry_engine.rb', line 55

def self.error_pointer(_validation_error)
  nil
end

.schema_class?(schema) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/request_handler/validation/dry_engine.rb', line 34

def self.schema_class?(schema)
  schema.respond_to?(:schema)
end

.schema_instance?(schema) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/request_handler/validation/dry_engine.rb', line 30

def self.schema_instance?(schema)
  schema.respond_to?(:call)
end

.to_result(result) ⇒ Object



45
46
47
48
49
# File 'lib/request_handler/validation/dry_engine.rb', line 45

def self.to_result(result)
  output = result.respond_to?(:to_h) ? result.to_h : result
  errors = result.respond_to?(:errors) ? result.errors.to_h : {}
  Result.new(output: output, errors: errors)
end

.valid_schema?(schema) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/request_handler/validation/dry_engine.rb', line 11

def self.valid_schema?(schema)
  schema_instance?(schema) || schema_class?(schema)
end

.validate(value, schema, options: {}) ⇒ Object



15
16
17
18
19
20
# File 'lib/request_handler/validation/dry_engine.rb', line 15

def self.validate(value, schema, options: {})
  value = value.deep_symbolize_keys if value.is_a?(Hash)
  to_result(call_schema(value, schema, options))
rescue Dry::Types::ConstraintError => e
  Result.new(output: nil, errors: { "" => e })
end

.validate!(value, schema, options: {}) ⇒ Object



38
39
40
41
42
43
# File 'lib/request_handler/validation/dry_engine.rb', line 38

def self.validate!(value, schema, options: {})
  validate(value, schema, options: options).tap do |result|
    valid = result.respond_to?(:valid?) ? result.valid? : result.success?
    raise Validation::Error unless valid
  end
end