Class: FlatMap::Errors
- Inherits:
-
ActiveModel::Errors
- Object
- ActiveModel::Errors
- FlatMap::Errors
- Defined in:
- lib/flat_map/errors.rb
Overview
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.
end
end
mapper = MyMapper.new(MyObject.new)
mapper.apply(:custom_attr => 'foo') # => false
mapper.errors[:custom_attr] # => ['cannot be foo']
Instance Method Summary collapse
-
#add(attr, *args) ⇒ Object
Overridden to add suffixing support for mappings of mappers with name suffix.
-
#empty? ⇒ Boolean
Overloaded to add
@preserved_errors
to the list of original@messages
. -
#initialize ⇒ Errors
constructor
Add
@preserved_errors
to object. -
#preserve(key, message) ⇒ Object
Postpone error.
Constructor Details
#initialize ⇒ Errors
Add @preserved_errors
to object.
26 27 28 29 |
# File 'lib/flat_map/errors.rb', line 26 def initialize(*) @preserved_errors = {} super end |
Instance Method Details
#add(attr, *args) ⇒ Object
Overridden to add suffixing support for mappings of mappers with name suffix
52 53 54 55 |
# File 'lib/flat_map/errors.rb', line 52 def add(attr, *args) attr = :"#{attr}_#{@base.suffix}" if attr != :base && @base.suffixed? super end |
#empty? ⇒ Boolean
Overloaded to add @preserved_errors
to the list of original @messages
. @preserved_errors
are cleared after this method call.
43 44 45 46 47 48 49 |
# 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 |
#preserve(key, message) ⇒ Object
Postpone error. It will be added to @messages
later, on empty?
method call.
36 37 38 |
# File 'lib/flat_map/errors.rb', line 36 def preserve(key, ) @preserved_errors[key] = end |