Sha256: 2b9b66d3f2c876fe6c8f98b482de712def053b3aa9b0a2695173a38036611109

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

module Yema
  class Rule
    class StrongType < self

      attr_reader :type, :strict, :member_type

      def initialize(attribute_name, options={})
        super
        extract_options(options)
      end

      def self.required_options
        [:type]
      end

      def matches?(value)
        raise ArgumentError if member_type && !value.respond_to?(:all?)

        return true if (strict == :allow_nil && value.nil?)
        Utils.type_matches?(value, type) && member_type_matches?(value)
      end

      private

      def extract_options(options)
        @type        = options.fetch(:type)
        @member_type = options.fetch(:member_type, nil)
        @strict      = options.fetch(:strict, :high)
        assert_options_value
      end

      def assert_options_value
        raise InvalidOptionError, "Strict option only accept [:high, :allow_nil]" unless [:high, :allow_nil].include?(strict)
      end

      def member_type_matches?(value)
        return value.all?{ |v| Utils.type_matches?(v, member_type) } if member_type
        true
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
yema-0.0.3 lib/yema/rule/strong_type.rb