class FlatMap::Errors
Inherited from ActiveModel::Errors to slightly ease work when writing attributes in a way that can possibly result in an exception. If we’d want to add errors on that point and see them in the resulting object, we have to preserve them before owner’s run_validations!
method call, since it will clear all the errors.
After validation complete, preserved errors are added to the list of the original ones.
Usecase scenario:
class MyMapper < FlatMap::Mapper def custom_attr=(value) raise MyException, 'cannot be foo' if value == 'foo' rescue MyException => e errors.preserve :custom_attr, e.message end end mapper = MyMapper.new(MyObject.new) mapper.apply(:custom_attr => 'foo') # => false mapper.errors[:custom_attr] # => ['cannot be foo']
Public Class Methods
Add @preserved_errors
to object.
# File lib/flat_map/errors.rb, line 26 def initialize(*) @preserved_errors = {} super end
Public Instance Methods
Overridden to add suffixing support for mappings of mappers with name suffix
# File lib/flat_map/errors.rb, line 52 def add(attr, *args) attr = :"#{attr}_#{@base.suffix}" if attr != :base && @base.suffixed? super end
Overloaded to add @preserved_errors
to the list of original @messages
. @preserved_errors
are cleared after this method call.
# File lib/flat_map/errors.rb, line 43 def empty? unless @preserved_errors.empty? @preserved_errors.each{ |key, value| add(key, value) } @preserved_errors.clear end super end
Postpone error. It will be added to @messages
later, on empty?
method call.
@param [String, Symbol] key @param [String] message
# File lib/flat_map/errors.rb, line 36 def preserve(key, message) @preserved_errors[key] = message end