Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/fields.rb

Overview

:nodoc

Instance Method Summary collapse

Instance Method Details

#defaultsHash

Returns the default values for the fields on the document.

Examples:

Get the defaults.

Person.defaults

Returns:

  • (Hash)

    The field defaults.



72
73
74
75
76
77
78
# File 'lib/mongoid/fields.rb', line 72

def defaults
  fields.inject({}) do |defs, (field_name,field)|
    next(defs) if field.default.nil?
    defs[field_name.to_s] = field.default
    defs
  end
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



37
38
39
40
# File 'lib/mongoid/fields.rb', line 37

def field(name, options = {})
  access = name.to_s
  set_field(access, options)
end

#fieldsHash

Return the fields for this class.

Examples:

Get the fields.

Person.fields

Returns:

  • (Hash)

    The fields for this document.

Since:

  • 2.0.0.rc.6



50
51
52
# File 'lib/mongoid/fields.rb', line 50

def fields
  @fields ||= {}
end

#fields=(fields) ⇒ Object

Set the fields for the class.

Examples:

Set the fields.

Person.fields = fields

Parameters:

  • fields (Hash)

    The hash of fields to set.

Since:

  • 2.0.0.rc.6



62
63
64
# File 'lib/mongoid/fields.rb', line 62

def fields=(fields)
  @fields = fields
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



90
91
92
93
# File 'lib/mongoid/fields.rb', line 90

def inherited(subclass)
  super
  subclass.fields = fields.dup
end