forked from pat/thinking-sphinx
/
facet_collection.rb
51 lines (40 loc) · 1.4 KB
/
facet_collection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module ThinkingSphinx
class FacetCollection < Hash
attr_accessor :arguments
def initialize(arguments)
@arguments = arguments.clone
@attribute_values = {}
@facets = []
end
def add_from_results(facet, results)
facet = facet_from_object(results.first, facet) if facet.is_a?(String)
self[facet.name] ||= {}
@attribute_values[facet.name] ||= {}
@facets << facet
results.each_with_groupby_and_count { |result, group, count|
facet_value = facet.value(result, group)
self[facet.name][facet_value] ||= 0
self[facet.name][facet_value] += count
@attribute_values[facet.name][facet_value] = group
}
end
def for(hash = {})
arguments = @arguments.clone
options = arguments.extract_options!
options[:with] ||= {}
hash.each do |key, value|
attrib = facet_for_key(key).attribute_name
options[:with][attrib] = @attribute_values[key][value]
end
arguments << options
ThinkingSphinx::Search.search *arguments
end
private
def facet_for_key(key)
@facets.detect { |facet| facet.name == key }
end
def facet_from_object(object, name)
object.sphinx_facets.detect { |facet| facet.attribute_name == name }
end
end
end