@@ -37,28 +37,45 @@ module FieldTypes
37
37
38
38
class << self
39
39
40
- # Gets a field class given its mapping identifier .
40
+ # Resolves the user-provided field type to the field type class .
41
41
#
42
42
# @example
43
43
# Mongoid::FieldTypes.get(:point)
44
44
#
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
50
59
end
51
60
52
61
# Defines a field type mapping, for later use in field :type option.
53
62
#
54
63
# @example
55
64
# Mongoid::FieldTypes.define(:point, Point)
56
65
#
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.
58
69
# @param [ Class ] klass the class of the defined type, which must
59
70
# 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
62
79
end
63
80
64
81
delegate :delete , to : :mapping
@@ -69,25 +86,6 @@ def define(type, klass)
69
86
def mapping
70
87
@mapping ||= DEFAULT_ALIASES . dup
71
88
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
91
89
end
92
90
end
93
91
end
0 commit comments