Class: Concen::Visit::Page

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document
Defined in:
app/models/concen/visit/page.rb

Class Method Summary collapse

Class Method Details

.aggregate_count_by_time(*args) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/models/concen/visit/page.rb', line 47

def self.aggregate_count_by_time(*args)
  options = args.extract_options!
  if hour = options[:hour]
    hour = hour.to_i
    current_time = Time.now.utc
    end_time = options[:start_time] || Time.utc(current_time.year, current_time.month, current_time.day, current_time.hour)
    start_time = end_time - (hour-1).hours
    hours = []
    (0..hour-1).each do |h|
      hours << (end_time - h.hours).to_i
    end

    map = <<-EOF
      function() {
        var hours = #{hours.to_json};
        for (index in hours) {
          if (this.hour.getTime() == hours[index]*1000) {
            emit(hours[index], this.count);
          } else {
            emit(hours[index], 0);
          };
        };

      }
    EOF

    reduce = <<-EOF
      function(time, counts) {
        var count = 0;
        for (index in counts) { count += counts[index]; };
        return count;
      }
    EOF

    query = {:hour => {"$gte" => start_time, "$lte" => end_time}}

    begin
      results = self.collection.map_reduce(map, reduce, :out => {:inline => 1}, :raw => true, :query => query)["results"]
      results = results.sort { |x,y| x["id"] <=> y["id"] }
      results = results.map do |result|
        time = result["_id"].to_i
        time *= 1000 if options[:precision] == "millisecond"
        [time, result["value"].to_i]
      end
    rescue
      results = []
    end

    return results
  end
end

.aggregate_count_by_url(*args) ⇒ Object



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
# File 'app/models/concen/visit/page.rb', line 16

def self.aggregate_count_by_url(*args)
  options = args.extract_options!

  map = <<-EOF
    function() {
      emit(this.url, this.count);
    }
  EOF

  reduce = <<-EOF
    function(time, counts) {
      var count = 0;
      for (index in counts) { count += counts[index]; };
      return count;
    }
  EOF

  begin
    results = self.collection.map_reduce(map, reduce, :out => {:inline => 1}, :raw => true)["results"]
    results = results.sort {|x,y| y["value"] <=> x["value"]}
    results = results[0..options[:limit]-1] if options[:limit]
    results = results.map do |result|
      [result["_id"], result["value"].to_i]
    end
  rescue
    results = []
  end

  return results
end