Last active
August 9, 2016 10:55
-
-
Save zapo/7d2a1632901766408bec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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