Skip to content

Instantly share code, notes, and snippets.

@zapo
Last active August 9, 2016 10:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zapo/7d2a1632901766408bec to your computer and use it in GitHub Desktop.
Save zapo/7d2a1632901766408bec to your computer and use it in GitHub Desktop.
module ActiveModel
class ErrorsSerializer < Serializer
def serialize object
@objects_hash ||= {}
return {} if @objects_hash.has_key?(object.object_id)
@objects_hash[object.object_id] = object
object.errors.to_hash.merge(object.class.reflect_on_all_associations.inject({}) { |m, assoc|
next m unless
object.class.respond_to?(:nested_attributes_options) &&
object.class.nested_attributes_options.has_key?(assoc.name) &&
assoc.validate?
target = object.send(assoc.name)
if assoc.collection?
errors = {}
target.each_with_index do |o, i|
serialized = serialize(o)
errors[i] = serialized unless serialized.empty?
end
m[assoc.name] = errors unless errors.empty?
else
serialized = serialize(target)
m[assoc.name] = serialized unless serialized.empty?
end
m
})
end
def serializable_hash
serialize(object)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment