2015-03-27 04:57:50 +08:00
|
|
|
# Helper functions for dealing with errors and objects that have
|
|
|
|
# child objects with errors
|
|
|
|
module HasErrors
|
2016-07-15 11:36:06 +08:00
|
|
|
attr_reader :errors
|
2019-01-04 01:03:01 +08:00
|
|
|
attr_accessor :forbidden, :not_found, :conflict
|
2015-03-27 04:57:50 +08:00
|
|
|
|
|
|
|
def errors
|
|
|
|
@errors ||= ActiveModel::Errors.new(self)
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_child(obj)
|
|
|
|
return true if obj.valid?
|
|
|
|
add_errors_from(obj)
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def rollback_with!(obj, error)
|
2016-05-05 20:58:25 +08:00
|
|
|
obj.errors.add(:base, error)
|
2015-03-27 04:57:50 +08:00
|
|
|
rollback_from_errors!(obj)
|
|
|
|
end
|
|
|
|
|
|
|
|
def rollback_from_errors!(obj)
|
|
|
|
add_errors_from(obj)
|
|
|
|
raise ActiveRecord::Rollback.new
|
|
|
|
end
|
|
|
|
|
2019-01-04 01:03:01 +08:00
|
|
|
def add_error(msg)
|
2019-04-30 14:58:18 +08:00
|
|
|
errors.add(:base, msg) unless errors[:base].include?(msg)
|
2019-01-04 01:03:01 +08:00
|
|
|
end
|
|
|
|
|
2015-03-27 04:57:50 +08:00
|
|
|
def add_errors_from(obj)
|
2019-01-04 01:03:01 +08:00
|
|
|
return if obj.blank?
|
|
|
|
|
|
|
|
if obj.is_a?(StandardError)
|
|
|
|
return add_error(obj.message)
|
2015-03-27 04:57:50 +08:00
|
|
|
end
|
2019-01-04 01:03:01 +08:00
|
|
|
|
|
|
|
obj.errors.full_messages.each { |msg| add_error(msg) }
|
2015-03-27 04:57:50 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|