Class: Sequent::Core::Helpers::DefaultValidators

Inherits:
Object
  • Object
show all
Defined in:
lib/sequent/core/helpers/default_validators.rb

Constant Summary collapse

VALIDATORS =
{
  Integer => ->(klass, field) do
    klass.validates_numericality_of field, only_integer: true, allow_nil: true, allow_blank: true
  end,
  Date => ->(klass, field) do
    klass.validates field, 'sequent::Core::Helpers::Date' => true
  end,
  Time => ->(klass, field) do
    klass.validates field, 'sequent::Core::Helpers::Time' => true
  end,
  DateTime => ->(klass, field) do
    klass.validates field, 'sequent::Core::Helpers::DateTime' => true
  end,
  Boolean => ->(klass, field) do
    klass.validates field, 'sequent::Core::Helpers::Boolean' => true
  end,
  String => ->(klass, field) do
    klass.validates field, 'sequent::Core::Helpers::String' => true
  end,
  Sequent::Core::Helpers::Secret => ->(klass, field) do
    klass.after_validation do |object|
      if object.errors&.any?
        object.send("#{field}=", nil)
      else
        raw_value = object.send(field)
        object.send("#{field}=", Sequent::Secret.new(raw_value)) if raw_value
      end
    end
  end,
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ DefaultValidators

Returns a new instance of DefaultValidators.



48
49
50
# File 'lib/sequent/core/helpers/default_validators.rb', line 48

def initialize(type)
  @type = type
end

Class Method Details

.for(type) ⇒ Object



44
45
46
# File 'lib/sequent/core/helpers/default_validators.rb', line 44

def self.for(type)
  new(type)
end

Instance Method Details

#add_validations_for(klass, field) ⇒ Object



52
53
54
55
# File 'lib/sequent/core/helpers/default_validators.rb', line 52

def add_validations_for(klass, field)
  validator = VALIDATORS[@type]
  validator&.call(klass, field)
end