3
3
module Mongoid
4
4
module Fields
5
5
6
- # Singleton module which contains a cache for field type definitions .
6
+ # Singleton module which contains a mapping of field types to field class .
7
7
# Custom field types can be configured.
8
8
module FieldTypes
9
- extend self
10
9
11
- # For fields defined with symbols use the correct class.
10
+ # The default mapping of field type symbol to class.
11
+ #
12
+ # @api private
12
13
DEFAULT_MAPPING = {
13
14
array : Array ,
14
15
bigdecimal : BigDecimal ,
@@ -35,32 +36,55 @@ module FieldTypes
35
36
time_with_zone : ActiveSupport ::TimeWithZone
36
37
} . with_indifferent_access . freeze
37
38
38
- def get ( value )
39
- value = value . to_sym if value . is_a? ( String )
40
- mapping [ value ] || handle_unmapped_type ( value )
41
- end
39
+ class << self
42
40
43
- def define ( symbol , klass )
44
- mapping [ symbol . to_sym ] = klass
45
- end
41
+ # Gets a field class given its mapping identifier.
42
+ #
43
+ # @example
44
+ # Mongoid::FieldTypes.get(:point)
45
+ #
46
+ # @param [ Symbol | String ] value the identifier of the defined type
47
+ def get ( value )
48
+ mapping [ value ] || handle_unmapped_type ( value )
49
+ end
46
50
47
- delegate :delete , to : :mapping
51
+ # Defines a field type mapping, for later use in field :type option.
52
+ #
53
+ # @example
54
+ # Mongoid::FieldTypes.define(:point, Point)
55
+ #
56
+ # @param [ Symbol ] symbol the symbol identifier of the defined type
57
+ # @param [ Class ] klass the class of the defined type, which must
58
+ # include mongoize and related methods.
59
+ def define ( symbol , klass )
60
+ mapping [ symbol . to_sym ] = klass
61
+ end
48
62
49
- private
63
+ delegate :delete , to : :mapping
50
64
51
- def mapping
52
- @mapping ||= DEFAULT_MAPPING . dup
53
- end
65
+ private
54
66
55
- def handle_unmapped_type ( type )
56
- return Object if type . nil?
57
-
58
- if type . is_a? ( Module )
59
- return Mongoid ::Boolean if type . to_s == 'Boolean'
60
- return type
67
+ # The memoized mapping of field type definitions to classes.
68
+ #
69
+ # @return [ ActiveSupport::HashWithIndifferentAccess<Symbol, Class> ] The memoized field mapping.
70
+ def mapping
71
+ @mapping ||= DEFAULT_MAPPING . dup
61
72
end
62
73
63
- nil
74
+ # Handles fallback for case where mapping does not contain the
75
+ # requested type.
76
+ #
77
+ # @return [ Class | nil ] The class to use as a fallback, or nil.
78
+ def handle_unmapped_type ( type )
79
+ return Object if type . nil?
80
+
81
+ if type . is_a? ( Module )
82
+ return Mongoid ::Boolean if type . to_s == 'Boolean'
83
+ return type
84
+ end
85
+
86
+ nil
87
+ end
64
88
end
65
89
end
66
90
end
0 commit comments