Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/fields.rb

Overview

:nodoc

Instance Method Summary collapse

Instance Method Details

#defaultsArray<String ] The names of all defaults.

Get a list of all the default fields for the model.

Examples:

Get a list of the defaults.

Model.defaults

Returns:

Since:

  • 2.4.0



171
172
173
# File 'lib/mongoid/fields.rb', line 171

def defaults
  non_proc_defaults + proc_defaults
end

#field(name, options = {}) ⇒ Field

Defines all the fields that are accessible on the Document For each field that is defined, a getter and setter will be added as an instance method to the Document.

Examples:

Define a field.

field :score, :type => Integer, :default => 0

Parameters:

  • name (Symbol)

    The name of the field.

  • options (Hash) (defaults to: {})

    The options to pass to the field.

Options Hash (options):

  • :type (Class)

    The type of the field.

  • :label (String)

    The label for the field.

  • :default (Object, Proc)

    The field’s default

Returns:

  • (Field)

    The generated field



190
191
192
193
194
195
196
197
198
# File 'lib/mongoid/fields.rb', line 190

def field(name, options = {})
  named = name.to_s
  check_field_name!(name)
  add_field(named, options).tap do
    descendants.each do |subclass|
      subclass.add_field(named, options)
    end
  end
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 behaviour of the old class_inheritable_accessor that was deprecated in Rails edge.

Examples:

Inherit from this class.

Person.inherited(Doctor)

Parameters:

  • subclass (Class)

    The inheriting class.

Since:

  • 2.0.0.rc.6



210
211
212
213
214
# File 'lib/mongoid/fields.rb', line 210

def inherited(subclass)
  super
  subclass.fields, subclass.non_proc_defaults, subclass.proc_defaults =
    fields.dup, non_proc_defaults.dup, proc_defaults.dup
end

#object_id_field?(name) ⇒ true, false

Is the field with the provided name a BSON::ObjectId?

Examples:

Is the field a BSON::ObjectId?

Person.object_id_field?(:name)

Parameters:

Returns:

  • (true, false)

    If the field is a BSON::ObjectId.

Since:

  • 2.2.0



226
227
228
229
230
231
# File 'lib/mongoid/fields.rb', line 226

def object_id_field?(name)
  field_name = name.to_s
  field_name = "_id" if field_name == "id"
  field = fields[field_name]
  field ? field.object_id_field? : false
end

#replace_field(name, type) ⇒ Serializable

Replace a field with a new type.

Examples:

Replace the field.

Model.replace_field("_id", String)

Parameters:

  • name (String)

    The name of the field.

  • type (Class)

    The new type of field.

Returns:

Since:

  • 2.1.0



244
245
246
247
# File 'lib/mongoid/fields.rb', line 244

def replace_field(name, type)
  defaults.delete_one(name)
  add_field(name, fields[name].options.merge(:type => type))
end