Method: Sunspot::Search::StatFacet#rows

Defined in:
lib/search/stat_facet.rb

#rowsObject



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
# File 'lib/search/stat_facet.rb', line 13

def rows
  #sort options :count or :stat_field 
  @options[:sort] ||= :count
  @options[:type] ||= "sum"
  @options[:limit] ||= -1
  @sort = false
  @rows ||=
  begin
    if @search.stat_response.present? && @search.stat_response['stats_fields'].present?
      if @options[:facet].present?
        stat = @search.stat_response['stats_fields'][@field.indexed_name]
        data = stat.nil? ? [] : stat['facets'][@options[:facet].indexed_name]
        @sort = true
      else
        data = @search.stat_response['stats_fields'].to_a
      end
    end

    rows = []

    data.collect do |stat, value|
      rows << StatRow.new(stat, value[@options[:type]], value, self) if value.present?
    end

    if @options[:sort] == :count
      rows.sort! { |lrow, rrow| rrow.value <=> lrow.value }
    else
      rows.sort! { |lrow, rrow| lrow.stat_field <=> rrow.stat_field }
    end if @sort
    rows.empty? ? [] : rows[0..@options[:limit]]
  rescue Exception => e
    puts "Sunspot Stats error: #{e.message} \n\n #{e.backtrace}"
    return []
  end
end