Class: Tram::Policy::Errors

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Instance Attribute Details

#policyTram::Policy (readonly)



15
16
17
# File 'lib/tram/policy/errors.rb', line 15

def policy
  @policy
end

Instance Method Details

#add(message = nil, **tags) ⇒ self

Adds error message to the collection

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
# File 'lib/tram/policy/errors.rb', line 23

def add(message = nil, **tags)
  message ||= tags.delete(:message)
  raise ArgumentError.new("Error message should be defined") unless message

  @set << Tram::Policy::Error.new(@policy.t(message, tags), **tags)
  self
end

#by_tags(**filter) ⇒ Hash<Symbol, Object>

Selects errors filtered by tags



45
46
47
48
# File 'lib/tram/policy/errors.rb', line 45

def by_tags(**filter)
  filter = filter.to_a
  reject { |error| (filter - error.to_h.to_a).any? }
end

#eachEnumerator<Tram::Policy::Error>

Iterates by collected errors



36
37
38
# File 'lib/tram/policy/errors.rb', line 36

def each
  @set.each { |error| yield(error) }
end

#empty?(&block) ⇒ Boolean

Checks whether a collection is empty



54
55
56
# File 'lib/tram/policy/errors.rb', line 54

def empty?(&block)
  block ? !any?(&block) : !any?
end

#full_messagesArray<String>

The array of ordered error messages with error tags info



70
71
72
# File 'lib/tram/policy/errors.rb', line 70

def full_messages
  @set.map(&:full_message).sort
end

#merge(other, **options) ⇒ Object

Merges other collection to the current one and returns new collection with the current scope

param [Tram::Policy::Errors] other Collection to be merged yieldparam [Hash<Symbol, Object>]

Examples:

Add some tag to merged errors

policy.merge(other) { |err| err[:source] = "other" }


83
84
85
86
87
88
89
90
91
92
# File 'lib/tram/policy/errors.rb', line 83

def merge(other, **options)
  return self unless other.is_a?(self.class)

  other.each do |err|
    new_err = block_given? ? yield(err.to_h) : err.to_h
    add new_err.merge(options)
  end

  self
end

#messagesArray<String>

The array of ordered error messages



62
63
64
# File 'lib/tram/policy/errors.rb', line 62

def messages
  @set.map(&:message).sort
end