Skip to content

Instantly share code, notes, and snippets.

@ElMassimo
Created October 12, 2015 23:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElMassimo/f59432e4211c6fbb6e04 to your computer and use it in GitHub Desktop.
Save ElMassimo/f59432e4211c6fbb6e04 to your computer and use it in GitHub Desktop.
Mongoid: No Heritage
module Mongoid
# Public: Allows to use inheritance to reuse logic, without using Single-
# Collection Inheritance, storing the model and superclass in different
# collections.
module NoHeritage
extend ActiveSupport::Concern
included do
# Internal: Preserve the default storage options instead of storing in the
# same collection than the superclass.
delegate :storage_options, to: :class
end
module ClassMethods
# Internal: Prevent adding _type in query selectors, and adding an index
# for _type.
def hereditary?
false
end
# Internal: Prevent Mongoid from defining a _type getter and setter.
def field(name, options = {})
super unless name.to_sym == :_type
end
# Internal: Preserve the default storage options instead of storing in the
# same collection than the superclass.
def inherited(subclass)
super
def subclass.storage_options
@storage_options ||= storage_options_defaults
end
end
end
end
end
@nofxx
Copy link

nofxx commented May 26, 2016

"hacky at best, more likely a problem waiting for the next Mongoid update to blow up"

And helluv good idea! Let's gem this!

EDIT: Also, to add on your pro list: Avoids using :_type on every search!

@benglewis
Copy link

Hi ElMassimo,

What is the license on this code? Can we use it freely for commercial use without attribution?

Thank you!

Warmest regards,

Ben

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment