Module: ActiveAdmin::Dry::Validation::DSL

Defined in:
lib/activeadmin/dry/validation/dsl.rb

Instance Method Summary collapse

Instance Method Details

#schema(outer_schema: nil, &block) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/activeadmin/dry/validation/dsl.rb', line 5

def schema(outer_schema: nil, &block) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  if block_given?
    result = ::Dry::Validation.Schema(::Dry::Validation::Schema::Params, {}, &block)
  elsif outer_schema.present? && outer_schema.is_a?(::Dry::Validation::Schema)
    result = outer_schema
  else
    result
  end
  controller do
    before_action :ensure_schema, only: %i[create update]

    define_method(:schema) do
      result
    end

    define_method(:ensure_schema) do
      params[:id].blank? ? build_resource : assign_attributes(resource, resource_params)
      action = params[:id].blank? ? :new : :edit
      schema.call(resource_params.first.to_h).errors.each do |rule, messages|
        messages.each { |message| resource.errors.add(rule, message) }
      end
      return render action unless resource.errors.empty?
    end
  end
end