Last active
August 29, 2015 14:13
-
-
Save mfpiccolo/6ac009943bf4f0aae10f to your computer and use it in GitHub Desktop.
A active record monkey patch to make serialization easy with active model serializers
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
# Monkey patch for ActiveRecord::Base to return serialized JSON in the format | |
# of an ActiveModel::Serializer. | |
module SerializedJson | |
extend ActiveSupport::Concern | |
def to_serial(serializer=nil, opts={}) | |
if self.respond_to?(:map) | |
serializer ||= (self.base_class.name + "Serializer").constantize | |
serialized_collection = self.map do |resource| | |
serializer.new(resource).as_json[base_class.name.underscore] | |
end | |
{ base_class.name.underscore.pluralize => serialized_collection } | |
else | |
serializer ||= (self.class.name + "Serializer").constantize | |
root = opts[:root] || false | |
json = serializer.new(self, root: root).as_json | |
end | |
end | |
end | |
ActiveRecord::Base.send(:include, SerializedJson) | |
ActiveRecord::Associations::CollectionProxy.send(:include, SerializedJson) | |
ActiveRecord::Relation.send(:include, SerializedJson) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment