Sha256: 39be648ed5fd1d58265d403e992c26b65d22fbb9fa187b55b16f1ee80e0d10de

Contents?: true

Size: 1.08 KB

Versions: 3

Compression:

Stored size: 1.08 KB

Contents

# frozen_string_literal: true

class Acfs::Resource
  module Validation
    def remote_errors
      @remote_errors ||= ActiveModel::Errors.new self
    end

    def remote_errors=(errors)
      if errors.respond_to?(:each_pair)
        errors.each_pair do |field, errs|
          Array(errs).each do |err|
            self.errors.add field.to_sym, err
            remote_errors.add field.to_sym, err
          end
        end
      else
        Array(errors).each do |err|
          self.errors.add :base, err
          remote_errors.add :base, err
        end
      end
    end

    def save!(**kwargs)
      unless valid?(new? ? :create : :save)
        raise ::Acfs::InvalidResource.new resource: self, errors: errors.to_a
      end

      super
    end

    if ::ActiveModel.version >= Gem::Version.new('6.1')
      def valid?(*args)
        super

        remote_errors.each {|e| errors.add(e.attribute, e.message) }
        errors.empty?
      end
    else
      def valid?(*args)
        super

        remote_errors.each {|f, e| errors.add(f, e) }
        errors.empty?
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
acfs-2.0.0 lib/acfs/resource/validation.rb
acfs-1.7.0 lib/acfs/resource/validation.rb
acfs-1.6.0 lib/acfs/resource/validation.rb