lib/tram/policy/errors.rb in tram-policy-1.0.1 vs lib/tram/policy/errors.rb in tram-policy-2.0.0
- old
+ new
@@ -1,32 +1,34 @@
class Tram::Policy
+ #
# 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.
#
class Errors
include Enumerable
- # @!attribute [r] policy
- #
- # @return [Tram::Policy] the poplicy errors provided by
- #
- attr_reader :policy
+ # @!attribute [r] scope
+ # @return [Array<String>] the scope for error messages' translation
+ attr_reader :scope
# @!method add(message, tags)
# Adds error message to the collection
#
# @param [#to_s] message Either a message, or a symbolic key for translation
# @param [Hash<Symbol, Object>] tags Tags to be attached to the message
# @return [self] the collection
#
def add(message, **tags)
- tags = tags.merge(scope: policy.scope) unless tags.key?(:scope)
raise ArgumentError.new("Error message should be defined") unless message
- tap { @set << Tram::Policy::Error.new(message, **tags) }
+
+ tap do
+ tags = tags.merge(scope: scope) if message.is_a?(Symbol)
+ @set << Tram::Policy::Error.new(message, **tags)
+ end
end
# Iterates by collected errors
#
# @yeldparam [Tram::Policy::Error]
@@ -45,11 +47,11 @@
#
def filter(key = nil, **tags)
list = each_with_object(Set.new) do |error, obj|
obj << error if error.contain?(key, tags)
end
- self.class.new(policy, list)
+ self.class.new(scope: scope, errors: list)
end
# @!method empty?
# Checks whether a collection is empty
#
@@ -99,11 +101,11 @@
self
end
private
- def initialize(policy, errors = [])
- @policy = policy
- @set = Set.new(errors)
+ def initialize(**options)
+ @scope = options[:scope] || Error::DEFAULT_SCOPE
+ @set = Set.new options[:errors].to_a
end
end
end