Sha256: 374606ece98d06f1e47bdeba084555183afaee1bcafb9092e7d412ba73af0b84

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

require 'active_support'
require 'active_support/core_ext/module/delegation'
require 'active_model/validator'
require 'active_model/validations'
require 'active_model/naming'
require 'active_model/callbacks'
require 'active_model/translation'
require 'active_model/errors'

module Might
  # Build singleton validation class for specified attribute name
  # @example you need a nice validator for a first_name
  #   validator_klass = ValueValidator.build('first_name', presence: true, length: { minimum: 3 })
  #   validator = validator_klass.new('Bo')
  #   validator.valid? #=> false
  #   validator.errors.full_messages #=> ['First name is too short (minimum is 3 characters)']
  #
  module FilterValueValidator
    module_function

    # Validates if Parameter is undefined or not
    class DefinedValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, _value)
        record.errors.add(attribute, :undefined_filter) if record.undefined?
      end
    end

    def build(definition)
      Struct.new(definition.as.to_sym) do
        include ActiveModel::Validations

        validates(definition.as, definition.validations) if definition.validations.present?
        validates(definition.as, :'might/filter_value_validator/defined' => true)

        define_method(:undefined?) { definition.undefined? }

        define_singleton_method :model_name do
          ActiveModel::Name.new(Might, nil, 'Might')
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
might-0.7.1 lib/might/filter_value_validator.rb
might-0.7.0 lib/might/filter_value_validator.rb
might-0.6.0 lib/might/filter_value_validator.rb
might-0.5.2 lib/might/filter_value_validator.rb