Module: HasErrors

Overview

Helper functions for dealing with errors and objects that have child objects with errors

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#conflictObject

Returns the value of attribute conflict.



6
7
8
# File 'lib/has_errors.rb', line 6

def conflict
  @conflict
end

#forbiddenObject

Returns the value of attribute forbidden.



6
7
8
# File 'lib/has_errors.rb', line 6

def forbidden
  @forbidden
end

#not_foundObject

Returns the value of attribute not_found.



6
7
8
# File 'lib/has_errors.rb', line 6

def not_found
  @not_found
end

Instance Method Details

#add_error(msg) ⇒ Object



28
29
30
# File 'lib/has_errors.rb', line 28

def add_error(msg)
  errors.add(:base, msg) if errors[:base].exclude?(msg)
end

#add_errors_from(obj) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/has_errors.rb', line 32

def add_errors_from(obj)
  return if obj.blank?

  return add_error(obj.message) if obj.is_a?(StandardError)

  obj.errors.full_messages.each { |msg| add_error(msg) }
end

#errorsObject



8
9
10
# File 'lib/has_errors.rb', line 8

def errors
  @errors ||= ActiveModel::Errors.new(self)
end

#rollback_from_errors!(obj) ⇒ Object

Raises:

  • (ActiveRecord::Rollback.new)


23
24
25
26
# File 'lib/has_errors.rb', line 23

def rollback_from_errors!(obj)
  add_errors_from(obj)
  raise ActiveRecord::Rollback.new, obj.errors.full_messages.join("\n")
end

#rollback_with!(obj, error, **kwargs) ⇒ Object



18
19
20
21
# File 'lib/has_errors.rb', line 18

def rollback_with!(obj, error, **kwargs)
  obj.errors.add(:base, error, **kwargs)
  rollback_from_errors!(obj)
end

#validate_child(obj) ⇒ Object



12
13
14
15
16
# File 'lib/has_errors.rb', line 12

def validate_child(obj)
  return true if obj.valid?
  add_errors_from(obj)
  false
end