Sha256: f9a5087544a40ad3f884fa239b039324846edcaaddb1ff9714c29e2c7dbea3b3

Contents?: true

Size: 1.28 KB

Versions: 14

Compression:

Stored size: 1.28 KB

Contents

module Grape
  module Validations
    class DefaultValidator < Base
      def initialize(attrs, options, required, scope, opts = {})
        @default = options
        super
      end

      def validate_param!(attr_name, params)
        return if params.key? attr_name
        params[attr_name] = if @default.is_a? Proc
                              @default.call
                            elsif @default.frozen? || !duplicatable?(@default)
                              @default
                            else
                              duplicate(@default)
                            end
      end

      def validate!(params)
        attrs = AttributesIterator.new(self, @scope, params)
        attrs.each do |resource_params, attr_name|
          if resource_params.is_a?(Hash) && resource_params[attr_name].nil?
            validate_param!(attr_name, resource_params)
          end
        end
      end

      private

      # return true if we might be able to dup this object
      def duplicatable?(obj)
        !obj.nil? &&
          obj != true &&
          obj != false &&
          !obj.is_a?(Symbol) &&
          !obj.is_a?(Numeric)
      end

      # make a best effort to dup the object
      def duplicate(obj)
        obj.dup
      rescue TypeError
        obj
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
grape-1.2.4 lib/grape/validations/validators/default.rb
grape-1.2.3 lib/grape/validations/validators/default.rb
grape-1.2.2 lib/grape/validations/validators/default.rb
grape-1.2.1 lib/grape/validations/validators/default.rb
grape-1.2.0 lib/grape/validations/validators/default.rb
grape-1.1.0 lib/grape/validations/validators/default.rb
grape-1.0.3 lib/grape/validations/validators/default.rb
grape-1.0.2 lib/grape/validations/validators/default.rb
grape-1.0.1 lib/grape/validations/validators/default.rb
grape-1.0.0 lib/grape/validations/validators/default.rb
grape-0.19.2 lib/grape/validations/validators/default.rb
grape-0.19.1 lib/grape/validations/validators/default.rb
grape-0.19.0 lib/grape/validations/validators/default.rb
grape-0.18.0 lib/grape/validations/validators/default.rb