Sha256: ed3d5fa87e123d998eea18b56d8325713fccbad5d999b885592777e1a8762130

Contents?: true

Size: 1010 Bytes

Versions: 11

Compression:

Stored size: 1010 Bytes

Contents

require 'hermod/validators/base'

module Hermod
  module Validators
    # This checks if the given value is an instance of a certain class
    class TypeChecker < Base

      attr_reader :expected_class, :checker

      # Sets up the validator with the class it is expected to be. You can
      # optionally pass a block to customise the class matching logic
      #
      # Examples
      #
      #   TypeChecker.new(Integer)
      #
      #   TypeChecker.new(Date) { |value| value.respond_to? :strftime }
      #
      def initialize(expected_class, &block)
        @expected_class = expected_class
        @checker = block || proc { |value| value.is_a? expected_class }
      end

      private

      def test
        value.blank? || checker.call(value)
      end

      def message
        expected_class_name = expected_class.name.downcase
        join_word = (%w(a e i o u).include?(expected_class_name[0]) ? "an" : "a")
        "must be #{join_word} #{expected_class_name}"
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
hermod-2.5.0 lib/hermod/validators/type_checker.rb
hermod-2.4.1 lib/hermod/validators/type_checker.rb
hermod-2.4.0 lib/hermod/validators/type_checker.rb
hermod-2.2.0 lib/hermod/validators/type_checker.rb
hermod-2.1.0 lib/hermod/validators/type_checker.rb
hermod-1.2.9 lib/hermod/validators/type_checker.rb
hermod-1.2.8 lib/hermod/validators/type_checker.rb
hermod-1.2.7 lib/hermod/validators/type_checker.rb
hermod-1.2.6 lib/hermod/validators/type_checker.rb
hermod-1.2.5 lib/hermod/validators/type_checker.rb
hermod-1.2.4 lib/hermod/validators/type_checker.rb