Class: MongoODM::Document::Fields::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_odm/document/fields.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, options = {}) ⇒ Field

Creates a new document field.

Parameters:

  • name (String, Symbol)

    the name of the field.

  • type (Class)

    the Ruby type of the field. It should respond to ‘type_cast’. Use Boolean for true or false types.

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

    configuration options.

Options Hash (options):

  • :default (Object, Proc) — default: nil

    a default value for the field, or a lambda to evaluate when providing the default.



25
26
27
28
29
# File 'lib/mongo_odm/document/fields.rb', line 25

def initialize(name, type, options = {})
  @name = name.to_sym
  @type = type
  @options = options.to_options
end

Instance Attribute Details

#nameSymbol (readonly)

Returns the name of this field in the Document.

Returns:

  • (Symbol)

    the name of this field in the Document.



14
15
16
# File 'lib/mongo_odm/document/fields.rb', line 14

def name
  @name
end

#optionsHash (readonly)

Returns configuration options.

Returns:

  • (Hash)

    configuration options.



18
19
20
# File 'lib/mongo_odm/document/fields.rb', line 18

def options
  @options
end

#typeClass (readonly)

Returns the Ruby type of field.

Returns:

  • (Class)

    the Ruby type of field.



16
17
18
# File 'lib/mongo_odm/document/fields.rb', line 16

def type
  @type
end

Instance Method Details

#defaultObject

Returns The default value for this field if defined, or nil.

Returns:

  • (Object)

    The default value for this field if defined, or nil.



32
33
34
35
36
37
# File 'lib/mongo_odm/document/fields.rb', line 32

def default
  if options.has_key?(:default)
    default = options[:default]
    type_cast(default.respond_to?(:call) ? default.call : default)
  end
end

#type_cast(value) ⇒ Object

Attempt to coerce the passed value into this field’s type

Parameters:

  • value (Object)

    the value to coerce

Returns:

  • (Object)

    the value coerced into this field’s type

Raises:



43
44
45
46
# File 'lib/mongo_odm/document/fields.rb', line 43

def type_cast(value)
  raise MongoODM::Errors::TypeCastMissing.new(value, @type) unless @type.respond_to?(:type_cast)
  @type.type_cast(value)
end