Sha256: ba8330ea64542b1cc11eb56a2c3c1b1ed72a4ca19ea6c53f0713f4e57dabad67

Contents?: true

Size: 753 Bytes

Versions: 1

Compression:

Stored size: 753 Bytes

Contents

# frozen_string_literal: true

module SimpleValidate
  class ValidatesTypeOf < ValidatesBase
    SUPPORTED_TYPES = %i[string integer float boolean].freeze

    def initialize(attribute, options)
      @allow_nil = options[:allow_nil]
      @type = options[:as]

      raise ArgumentError unless @type && SUPPORTED_TYPES.include?(@type)

      super(attribute, options[:message] ||
        "must be #{Utils.article(@type)} #{@type}", options[:if] || proc { true })
    end

    def valid?(instance)
      val = instance.send(attribute)

      return true if val.nil? && @allow_nil == true

      if @type == :boolean
        [true, false].include? val
      else
        klass = Utils.classify(@type)
        val.is_a?(klass)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simple_validate-2.2.2 lib/simple_validate/validates_type_of.rb