Skip to content

Instantly share code, notes, and snippets.

@wyattisimo
Last active March 12, 2019 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattisimo/6e5b64b327c8fc978a3f80b90637696a to your computer and use it in GitHub Desktop.
Save wyattisimo/6e5b64b327c8fc978a3f80b90637696a to your computer and use it in GitHub Desktop.
Drills into related Mongoid models to create a single error message.
##
# Drills into related Mongoid models to create a single error message.
#
# @param obj [Object] An instance of a Mongoid model class.
# @param prefix [String] The class/attribute name prefix (for recursive calls).
#
# @return [String] A string of concatenated error messages.
#
def err_drill(obj, prefix = nil)
prefix = "#{obj.class.to_s.downcase}." if prefix.nil?
# Error messages for this object.
msg = obj.errors.messages.map do |error|
"(#{prefix}#{error[0].to_s.singularize}) #{error[1].join(", ")}"
end.join("; ")
# Look over the relations and concatenate their error messages.
obj.relations.each do |relation|
metadata = relation[1]
# Only drill into "child" relations.
if metadata.macro.match /(_many|_one)/
children = obj.send(metadata.name.to_sym)
children = [children] unless children.is_a? Array
children.each do |child|
if child.respond_to?(:errors) && child.errors.messages.empty? == false
msg << "; " << err_drill(child, "#{prefix}#{metadata.name.to_s.singularize}.")
end
end
end
end
return msg
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment