Class: Tram::Policy::Errors
- Inherits:
-
Object
- Object
- Tram::Policy::Errors
- Includes:
- Enumerable
- Defined in:
- lib/tram/policy/errors.rb
Overview
Enumerable collection of unique unordered validation errors
Notice: A collection is context-dependent;
it knows about a scope of policy it belongs to,
and how to translate error messages in that scope.
Instance Attribute Summary collapse
-
#scope ⇒ Array<String>
readonly
The scope for error messages’ translation.
Instance Method Summary collapse
-
#add(message, tags) ⇒ self
Adds error message to the collection.
-
#each ⇒ Enumerator<Tram::Policy::Error>
Iterates by collected errors.
-
#empty? ⇒ Boolean
Checks whether a collection is empty.
-
#filter(key = nil, tags) ⇒ Tram::Policy::Errors
Filter errors by optional key and tags.
-
#items ⇒ Array<Array>
The array of error items for translation.
-
#merge(other, options) {|hash| ... } ⇒ self
Merges other collection to the current one and returns new collection with the current scope.
-
#messages ⇒ Array<String>
The array of ordered error messages.
Instance Attribute Details
#scope ⇒ Array<String> (readonly)
Returns the scope for error messages’ translation.
14 15 16 |
# File 'lib/tram/policy/errors.rb', line 14 def scope @scope end |
Instance Method Details
#add(message, tags) ⇒ self
Adds error message to the collection
23 24 25 26 27 28 29 30 |
# File 'lib/tram/policy/errors.rb', line 23 def add(, **) raise ArgumentError.new("Error message should be defined") unless tap do = { scope: scope }.merge() if .is_a?(Symbol) @set << Tram::Policy::Error.new(, **) end end |
#each ⇒ Enumerator<Tram::Policy::Error>
Iterates by collected errors
37 38 39 |
# File 'lib/tram/policy/errors.rb', line 37 def each @set.each { |error| yield(error) } end |
#empty? ⇒ Boolean
Checks whether a collection is empty
60 61 62 |
# File 'lib/tram/policy/errors.rb', line 60 def empty?(&block) block ? !any?(&block) : !any? end |
#filter(key = nil, tags) ⇒ Tram::Policy::Errors
Filter errors by optional key and tags
48 49 50 51 52 53 |
# File 'lib/tram/policy/errors.rb', line 48 def filter(key = nil, **) list = each_with_object(Set.new) do |error, obj| obj << error if error.contain?(key, ) end self.class.new(scope: scope, errors: list) end |
#items ⇒ Array<Array>
The array of error items for translation
68 69 70 |
# File 'lib/tram/policy/errors.rb', line 68 def items @set.map(&:item) end |
#merge(other, options) {|hash| ... } ⇒ self
Merges other collection to the current one and returns new collection with the current scope
92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/tram/policy/errors.rb', line 92 def merge(other, **) return self unless other.is_a?(self.class) other.each do |err| key, opts = err.item opts = yield(opts) if block_given? add key, opts.merge() end self end |
#messages ⇒ Array<String>
The array of ordered error messages
76 77 78 |
# File 'lib/tram/policy/errors.rb', line 76 def @set.map(&:message).sort end |