Sha256: ef409fde687a1ad4c99c7c3eee45a0420ddf4dcc03c9c03d83fdd0cf1cdbda6f

Contents?: true

Size: 1.03 KB

Versions: 18

Compression:

Stored size: 1.03 KB

Contents

module Datacaster
  class Validator < Base
    @@validations = {}

    def self.create_active_model(validations)
      @@validations[validations] ||=
        Class.new do
          include ActiveModel::Validations

          attr_accessor :value

          def self.model_name
            ActiveModel::Name.new(self, nil, "ValidatorModel")
          end

          if validations.present?
            validates :value, validations
          end
        end.new
    end

    def initialize(validations)
      require 'active_model'

      if Config.i18n_module == SubstituteI18n
        raise NotImplementedError, "Using ActiveModel validations requires ruby-i18n or another i18n gem instead of datacaster's built-in", caller
      end
      @validator = self.class.create_active_model(validations)
    end

    def cast(object, runtime:)
      @validator.value = object
      @validator.valid? ? Datacaster.ValidResult(object) : Datacaster.ErrorResult(@validator.errors[:value])
    end

    def inspect
      "#<Datacaster::Validator>"
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
datacaster-4.1.0 lib/datacaster/validator.rb
datacaster-4.0.1 lib/datacaster/validator.rb
datacaster-3.3.1 lib/datacaster/validator.rb
datacaster-3.3.0 lib/datacaster/validator.rb
datacaster-3.2.7 lib/datacaster/validator.rb
datacaster-3.2.6 lib/datacaster/validator.rb
datacaster-3.2.5 lib/datacaster/validator.rb
datacaster-3.2.4 lib/datacaster/validator.rb
datacaster-3.2.3 lib/datacaster/validator.rb
datacaster-3.2.2 lib/datacaster/validator.rb
datacaster-3.2.1 lib/datacaster/validator.rb
datacaster-3.2.0 lib/datacaster/validator.rb
datacaster-3.1.5 lib/datacaster/validator.rb
datacaster-3.1.3 lib/datacaster/validator.rb
datacaster-3.1.2 lib/datacaster/validator.rb
datacaster-3.1.1 lib/datacaster/validator.rb
datacaster-3.1.0 lib/datacaster/validator.rb
datacaster-3.0.0 lib/datacaster/validator.rb