lib/datacaster/base.rb in datacaster-0.9.1 vs lib/datacaster/base.rb in datacaster-2.0.1

- old
+ new

@@ -1,5 +1,7 @@ +require "ostruct" + module Datacaster class Base def self.merge_errors(left, right) add_error_to_base = ->(hash, error) { hash[:base] ||= [] @@ -43,28 +45,57 @@ def then(other) ThenNode.new(self, other) end + def set_definition_context(definition_context) + @definition_context = definition_context + end + + def with_context(additional_context) + @definition_context.context = OpenStruct.new(additional_context) + self + end + def call(object) - Datacaster.ValidResult(object) + object = cast(object) + + return object if object.valid? || @cast_errors.nil? + + error_cast = @cast_errors.(object.errors) + + raise "#cast_errors must return Datacaster.ValidResult, currently it is #{error_cast.inspect}" unless error_cast.valid? + + Datacaster.ErrorResult( + @cast_errors.(object.errors).value, + meta: object.meta + ) end + def cast_errors(object) + @cast_errors = shortcut_definition(object) + self + end + def inspect "#<Datacaster::Base>" end private + def cast(object) + Datacaster.ValidResult(object) + end + # Translates hashes like {a: <IntegerChecker>} to <HashSchema {a: <IntegerChecker>}> # and arrays like [<IntegerChecker>] to <ArraySchema <IntegerChecker>> def shortcut_definition(definition) case definition when Datacaster::Base definition when Array if definition.length != 1 - raise ArgumentError.new("Datacaster: shorcut array definitions must have exactly 1 element in the array, e.g. [integer]") + raise ArgumentError.new("Datacaster: shortcut array definitions must have exactly 1 element in the array, e.g. [integer]") end ArraySchema.new(definition.first) when Hash HashSchema.new(definition) else