Created
September 11, 2014 18:33
-
-
Save jstejada/b33d1184ffdfc7b4e8a3 to your computer and use it in GitHub Desktop.
I did this with Mongoid
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
# 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