lib/datacaster/base.rb in datacaster-2.0.2 vs lib/datacaster/base.rb in datacaster-3.0.0
- old
+ new
@@ -1,7 +1,5 @@
-require "ostruct"
-
module Datacaster
class Base
def self.merge_errors(left, right)
add_error_to_base = ->(hash, error) {
hash[:base] ||= []
@@ -41,68 +39,59 @@
def *(other)
AndWithErrorAggregationNode.new(self, other)
end
+ def cast_errors(error_caster)
+ ContextNodes::ErrorsCaster.new(self, error_caster)
+ end
+
def then(other)
ThenNode.new(self, other)
end
- def set_definition_context(definition_context)
- @definition_context = definition_context
+ def with_context(context)
+ unless context.is_a?(Hash)
+ raise "with_context expected Hash as argument, got #{context.inspect} instead"
+ end
+ ContextNodes::UserContext.new(self, context)
end
- def with_context(additional_context)
- @definition_context.context = OpenStruct.new(additional_context)
- self
+ def call(object)
+ call_with_runtime(object, Runtimes::Base.new)
end
- def call(object)
- object = cast(object)
+ def call_with_runtime(object, runtime)
+ result = cast(object, runtime: runtime)
+ unless result.is_a?(Result)
+ raise RuntimeError.new("Caster should've returned Datacaster::Result, but returned #{result.inspect} instead")
+ end
+ result
+ end
- return object if object.valid? || @cast_errors.nil?
+ def with_runtime(runtime)
+ ->(object) do
+ call_with_runtime(object, runtime)
+ end
+ end
- 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
- )
+ def i18n_key(*keys, **args)
+ ContextNodes::I18n.new(self, I18nValues::Key.new(keys, args))
end
- def cast_errors(object)
- @cast_errors = shortcut_definition(object)
- self
+ def i18n_map_keys(mapping)
+ ContextNodes::I18nKeysMapper.new(self, mapping)
end
- def inspect
- "#<Datacaster::Base>"
+ def i18n_scope(scope, **args)
+ ContextNodes::I18n.new(self, I18nValues::Scope.new(scope, args))
end
- private
-
- def cast(object)
- Datacaster.ValidResult(object)
+ def i18n_vars(vars)
+ ContextNodes::I18n.new(self, I18nValues::Scope.new(nil, vars))
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: 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
- return definition if definition.respond_to?(:call)
- raise ArgumentError.new("Datacaster: Unknown definition #{definition.inspect}, which doesn't respond to #call")
- end
+ def inspect
+ "#<Datacaster::Base>"
end
end
end