lib/dry/schema/macros/dsl.rb in dry-schema-0.4.0 vs lib/dry/schema/macros/dsl.rb in dry-schema-0.5.0

- old
+ new

@@ -17,10 +17,15 @@ undef :nil? # @api private option :chain, default: -> { true } + # @!attribute [r] predicate_inferrer + # @return [PredicateInferrer] + # @api private + option :predicate_inferrer, default: proc { PredicateInferrer.new(compiler.predicates) } + # Specify predicates that should be applied to a value # # @api public def value(*predicates, **opts, &block) append_macro(Macros::Value) do |macro| @@ -73,23 +78,68 @@ append_macro(Macros::Array) do |macro| macro.value(*args, &block) end end + # Set type spec + # + # @param [Symbol, Array, Dry::Types::Type] + # + # @return [Macros::Key] + # + # @api public + def type(spec) + schema_dsl.set_type(name, spec) + self + end + private # @api private - def append_macro(macro_type, &block) + def append_macro(macro_type) macro = macro_type.new(schema_dsl: schema_dsl, name: name) yield(macro) if chain trace << macro self else macro end + end + + # @api private + def extract_type_spec(*args, nullable: false, set_type: true) + type_spec = args[0] + + is_type_spec = type_spec.is_a?(Dry::Schema::Processor) || + type_spec.is_a?(Symbol) && + type_spec.to_s.end_with?(QUESTION_MARK) + + type_spec = nil if is_type_spec + + predicates = Array(type_spec ? args[1..-1] : args) + + if type_spec + resolved_type = schema_dsl.resolve_type( + nullable && !type_spec.is_a?(::Array) ? [:nil, type_spec] : type_spec + ) + + type(resolved_type) if set_type + + type_predicates = predicate_inferrer[resolved_type] + + unless predicates.include?(type_predicates) + if type_predicates.is_a?(::Array) && type_predicates.size.equal?(1) + predicates.unshift(type_predicates[0]) + else + predicates.unshift(type_predicates) + end + end + end + + yield(*predicates, type_spec: type_spec) end end end end end