2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-03-26 15:57:50 -05:00
|
|
|
# Helper functions for dealing with errors and objects that have
|
|
|
|
# child objects with errors
|
|
|
|
module HasErrors
|
2019-01-03 11:03:01 -06:00
|
|
|
attr_accessor :forbidden, :not_found, :conflict
|
2015-03-26 15:57:50 -05:00
|
|
|
|
|
|
|
def errors
|
|
|
|
@errors ||= ActiveModel::Errors.new(self)
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_child(obj)
|
|
|
|
return true if obj.valid?
|
|
|
|
add_errors_from(obj)
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
2024-09-03 05:08:14 -05:00
|
|
|
def rollback_with!(obj, error, **kwargs)
|
|
|
|
obj.errors.add(:base, error, **kwargs)
|
2015-03-26 15:57:50 -05:00
|
|
|
rollback_from_errors!(obj)
|
|
|
|
end
|
|
|
|
|
|
|
|
def rollback_from_errors!(obj)
|
|
|
|
add_errors_from(obj)
|
2024-09-03 05:08:14 -05:00
|
|
|
raise ActiveRecord::Rollback.new, obj.errors.full_messages.join("\n")
|
2015-03-26 15:57:50 -05:00
|
|
|
end
|
|
|
|
|
2019-01-03 11:03:01 -06:00
|
|
|
def add_error(msg)
|
2024-05-27 05:27:13 -05:00
|
|
|
errors.add(:base, msg) if errors[:base].exclude?(msg)
|
2019-01-03 11:03:01 -06:00
|
|
|
end
|
|
|
|
|
2015-03-26 15:57:50 -05:00
|
|
|
def add_errors_from(obj)
|
2019-01-03 11:03:01 -06:00
|
|
|
return if obj.blank?
|
|
|
|
|
2023-01-09 06:10:19 -06:00
|
|
|
return add_error(obj.message) if obj.is_a?(StandardError)
|
2019-01-03 11:03:01 -06:00
|
|
|
|
|
|
|
obj.errors.full_messages.each { |msg| add_error(msg) }
|
2015-03-26 15:57:50 -05:00
|
|
|
end
|
|
|
|
end
|