Sha256: dc79cf6e39b21ca1ff9929895d8de42e4c9f3ee5612ecb7c549c60f5f937fc4b

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

gem 'dry-validation', '~> 1.5'
require "dry-validation"
require "reform/validation"
require "reform/form/dry/input_hash"

::Dry::Validation.load_extensions(:hints)

module Reform::Form::Dry
  class Contract < Dry::Validation::Contract
  end

  def self.included(includer)
    includer.send :include, Validations
    includer.extend Validations::ClassMethods
  end

  module Validations
    module ClassMethods
      def validation_group_class
        Group
      end
    end

    def self.included(includer)
      includer.extend(ClassMethods)
    end

    class Group
      include InputHash

      def initialize(options)
        @validator = options.fetch(:contract, Contract)
        @schema_inject_params = options.fetch(:with, {})
      end

      attr_reader :validator, :schema_inject_params, :block

      def instance_exec(&block)
        @block = block
      end

      def call(form)
        # when passing options[:schema] the class instance is already created so we just need to call
        # "call"
        return validator.call(input_hash(form)) unless validator.is_a?(Class) && @validator <= ::Dry::Validation::Contract

        dynamic_options = { form: form }
        inject_options = schema_inject_params.merge(dynamic_options)
        contract.new(**inject_options).call(input_hash(form))
      end

      def contract
        @contract ||= Class.new(validator, &block)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
reform-2.6.2 lib/reform/form/dry.rb
reform-2.6.1 lib/reform/form/dry.rb
reform-2.6.0 lib/reform/form/dry.rb