@@ -19,10 +19,11 @@ module Elasticsearch
19
19
module Model
20
20
21
21
# Keeps a global registry of classes that include `Elasticsearch::Model`
22
- #
22
+ # Keeps a global registry of index to class mappings
23
23
class Registry
24
24
def initialize
25
25
@models = [ ]
26
+ @indexes = { }
26
27
end
27
28
28
29
# Returns the unique instance of the registry (Singleton)
@@ -45,22 +46,64 @@ def self.all
45
46
__instance . models
46
47
end
47
48
49
+ def self . indexes
50
+ __instance . indexes
51
+ end
52
+
53
+ def self . add_index ( index , model )
54
+ __instance . add_index ( index , model )
55
+ end
56
+
48
57
# Adds a model to the registry
49
58
#
50
59
def add ( klass )
51
60
# Detect already loaded models and ensure that a duplicate is not stored
52
61
if i = @models . index { |_class | _class . name == klass . name }
53
62
@models [ i ] = klass
63
+ # clear the cached index map (autoloading in development causes this)
64
+ @indexes . clear
54
65
else
55
66
@models << klass
56
67
end
57
68
end
58
69
70
+ def add_index ( index , model )
71
+ @indexes [ index ] = model
72
+ end
73
+
59
74
# Returns a copy of the registered models
60
75
#
61
76
def models
62
77
@models . dup
63
78
end
79
+
80
+ def indexes
81
+ @indexes . dup
82
+ end
83
+
84
+ ##
85
+ # Find the model matching the given index and document type from a search hit
86
+ # Cache the index->model mapping for performance
87
+ # Clear the index cache when models are reloaded
88
+ def self . lookup ( index , type = nil )
89
+ if Registry . indexes . has_key? ( index )
90
+ # Cache hit
91
+ Registry . indexes [ index ]
92
+ else
93
+ # Cache bust
94
+ model = if type . nil? or type == "_doc"
95
+ # lookup strictly by index for generic document types
96
+ Registry . all . detect { |m | m . index_name == index }
97
+ else
98
+ # lookup using index and type
99
+ Registry . all . detect { |m | m . index_name == index and model . document_type == type }
100
+ end
101
+ # cache the index to model mapping
102
+ Registry . add_index ( index , model )
103
+ model
104
+ end
105
+ end
106
+
64
107
end
65
108
66
109
# Wraps a collection of models when querying multiple indices
0 commit comments