Sha256: 4e36291882b51aecbfd86e983d019d3af166d1c44a3d08e5d7a7f9ead534e16b

Contents?: true

Size: 1.62 KB

Versions: 2

Compression:

Stored size: 1.62 KB

Contents

require 'jschematic/element'

module Jschematic
  module Attributes
    class Type
      include Jschematic::Element

      attr_reader :type

      def initialize(type)
        @type = type
      end

      def accepts?(instance)
        return true unless type

        case type
        when /^object$/
          assert_kind_of([Hash], instance)
        when /^number$/
          assert_kind_of([Numeric], instance)
        when /^integer$/
          assert_kind_of([Integer], instance)
        when /^boolean$/
          assert_kind_of([TrueClass, FalseClass], instance)
        when /^null$/
          assert_kind_of([NilClass], instance)
        when /^any$/
          true
        when Array # union
          # TODO: this is gross. A specific Union type is likely called for
          type.any? do |union_type|
            begin
              if String===union_type
                Type.new(union_type).accepts?(instance)
              elsif Hash===union_type
                Schema.new(union_type).accepts?(instance)
              end
            rescue ValidationError
              false
            end
          end || fail_validation!(type, instance)
        else
          # TODO: probably worth just putting in explicit mapping for all
          # JSON schema types--there are only a few left
          assert_kind_of([constantize(type)], instance)
        end
      end

      private

      def assert_kind_of(klassen, instance)
        klassen.any?{ |klass| instance.kind_of?(klass) } || fail_validation!(klassen, instance)
      end

      def constantize(string)
        Kernel.const_get(string.capitalize)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
jschematic-0.1.0 lib/jschematic/attributes/type.rb
jschematic-0.0.9 lib/jschematic/attributes/type.rb