Module: Mongoid::Traversable::ClassMethods

Defined in:
lib/mongoid/traversable.rb

Overview

Class-level methods for the Traversable behavior.

Instance Method Summary collapse

Instance Method Details

#hereditary?true | false

Determines if the document is a subclass of another document.

Examples:

Check if the document is a subclass.

Square.hereditary?

Returns:

  • True if hereditary, false if not.



43
44
45
# File 'lib/mongoid/traversable.rb', line 43

def hereditary?
  !!(superclass < Mongoid::Document)
end

#inherited(subclass) ⇒ Object

When inheriting, we want to copy the fields from the parent class and set the on the child to start, mimicking the behavior of the old class_inheritable_accessor that was deprecated in Rails edge.

rubocop:disable Metrics/AbcSize

Examples:

Inherit from this class.

Person.inherited(Doctor)

Parameters:

  • The inheriting class.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/mongoid/traversable.rb', line 69

def inherited(subclass)
  super

  # Register the new subclass with the resolver subsystem
  Mongoid::ModelResolver.register(subclass)

  @_type = nil
  subclass.aliased_fields = aliased_fields.dup
  subclass.localized_fields = localized_fields.dup
  subclass.fields = fields.dup
  subclass.pre_processed_defaults = pre_processed_defaults.dup
  subclass.post_processed_defaults = post_processed_defaults.dup
  subclass._declared_scopes = Hash.new { |_hash, key| _declared_scopes[key] }
  subclass.discriminator_value = subclass.name

  # We need to do this here because the discriminator_value method is
  # overridden in the subclass above.
  subclass.include DiscriminatorRetrieval

  # We only need the _type field if inheritance is in play, but need to
  # add to the root class as well for backwards compatibility.
  return if fields.key?(discriminator_key)

  default_proc = -> { self.class.discriminator_value }
  field(discriminator_key, default: default_proc, type: String)
end

#root_classMongoid::Document

Returns the root class of the STI tree that the current class participates in. If the class is not an STI subclass, this returns the class itself.

Returns:

  • the root of the STI tree



52
53
54
55
56
57
# File 'lib/mongoid/traversable.rb', line 52

def root_class
  root = self
  root = root.superclass while root.hereditary?

  root
end