Skip to content

Instantly share code, notes, and snippets.

@jstejada
Created September 11, 2014 18:33
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 jstejada/b33d1184ffdfc7b4e8a3 to your computer and use it in GitHub Desktop.
Save jstejada/b33d1184ffdfc7b4e8a3 to your computer and use it in GitHub Desktop.
I did this with Mongoid
# Monkeypatching BSON::Object
module BSON
class ObjectId
# These aliases override default JSON representation of an ObjectId
# Spits a string id '540f51de6d61632c74020000', instead of
# { "$oid": '540f51de6d61632c74020000' }
alias :to_json :to_s
alias :as_json :to_s
end
end
# Monkeypatching Mongoid::Document
module Mongoid::Document
# Overrides ActiveModel::Serialization#serializable_hash for Mongoid Docs
# If needed, please refer to the original method documentation.
# Returns serialized_hash of any Mongoid::Document with following conditions:
#
# - For a root document (not embedded) the `:_id` field is replaced for
# `:id` field
# - For an embedded document :_id field is completely excluded
#
# It gracefully keeps any other :only, :except, and :methods
# options originally passed in the `options` hash
def serializable_hash(options = nil)
options ||= {}
if self.embedded?
options[:except] = Array(options[:except]) << :_id
if options.has_key?(:methods)
options[:methods] = Array(options[:methods])
options[:methods].delete(:id)
end
else
options[:methods] = Array(options[:methods]) << :id
options[:except] = Array(options[:except]) << :_id
end
super options
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment