@@ -37,28 +37,45 @@ module FieldTypes
3737
3838 class << self
3939
40- # Gets a field class given its mapping identifier .
40+ # Resolves the user-provided field type to the field type class .
4141 #
4242 # @example
4343 # Mongoid::FieldTypes.get(:point)
4444 #
45- # @param [ Symbol | String | Class | nil ] type the identifier of the defined
46- # type, or a class to pass-through, or nil.
47- # @return [ Class | nil ] The mapped type class, or nil.
48- def get ( type )
49- mapping [ type ] || handle_unmapped_type ( type )
45+ # @param [ Class | Symbol | String | Class ] field_type The field
46+ # type class or its string or symbol alias.
47+ #
48+ # @return [ Class | nil ] The underlying field type class, or nil if
49+ # string or symbol was passed and it is not mapped to any class.
50+ def get ( field_type )
51+ case field_type
52+ when Class
53+ type
54+ when Symbol , String
55+ mapping [ field_type ]
56+ else
57+ raise Mongoid ::Errors ::InvalidFieldType . new ( self . name , field , field_type )
58+ end
5059 end
5160
5261 # Defines a field type mapping, for later use in field :type option.
5362 #
5463 # @example
5564 # Mongoid::FieldTypes.define(:point, Point)
5665 #
57- # @param [ Symbol ] type the symbol identifier of the defined type
66+ # @param [ Symbol | String ] field_type_alias the string or symbol
67+ # alias of the defined type. The alias will be accessible as a string
68+ # or a symbol regardless of the type passed to this method.
5869 # @param [ Class ] klass the class of the defined type, which must
5970 # include mongoize, demongoize, and evolve methods.
60- def define ( type , klass )
61- mapping [ type ] = klass
71+ def define_alias ( field_type_alias , klass )
72+ unless field_type_alias . is_a? ( String ) || field_type_alias . is_a? ( Symbol )
73+ raise Mongoid ::Errors ::InvalidFieldTypeAliasName . new ( field_type_alias )
74+ end
75+ unless klass . is_a? ( Class )
76+ raise Mongoid ::Errors ::InvalidFieldTypeAliasValue . new ( field_type_alias , klass )
77+ end
78+ mapping [ field_type_alias ] = klass
6279 end
6380
6481 delegate :delete , to : :mapping
@@ -69,25 +86,6 @@ def define(type, klass)
6986 def mapping
7087 @mapping ||= DEFAULT_ALIASES . dup
7188 end
72-
73- private
74-
75- # Handles fallback for case where mapping does not contain the
76- # requested type.
77- #
78- # @param [ Symbol | String | Class | nil ] type the identifier of the defined
79- # type, or a class, or nil.
80- # @return [ Class | nil ] The class to use as a fallback, or nil.
81- def handle_unmapped_type ( type )
82- return Object if type . nil?
83-
84- if type . is_a? ( Module )
85- return Mongoid ::Boolean if type . to_s == 'Boolean'
86- return type
87- end
88-
89- nil
90- end
9189 end
9290 end
9391 end
0 commit comments