Skip to content

Instantly share code, notes, and snippets.

@mfpiccolo
Last active August 29, 2015 14:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfpiccolo/6ac009943bf4f0aae10f to your computer and use it in GitHub Desktop.
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
# 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