33module Mongoid
44 module Fields
55
6- # Singleton module which contains a cache for field type definitions .
6+ # Singleton module which contains a mapping of field types to field class .
77 # Custom field types can be configured.
88 module FieldTypes
9- extend self
109
11- # For fields defined with symbols use the correct class.
10+ # The default mapping of field type symbol to class.
11+ #
12+ # @api private
1213 DEFAULT_MAPPING = {
1314 array : Array ,
1415 bigdecimal : BigDecimal ,
@@ -35,32 +36,55 @@ module FieldTypes
3536 time_with_zone : ActiveSupport ::TimeWithZone
3637 } . with_indifferent_access . freeze
3738
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
4240
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
4650
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
4862
49- private
63+ delegate :delete , to : :mapping
5064
51- def mapping
52- @mapping ||= DEFAULT_MAPPING . dup
53- end
65+ private
5466
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
6172 end
6273
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
6488 end
6589 end
6690 end
0 commit comments