Module: VisitCounter::ClassMethods

Defined in:
lib/visit_counter_updater/visit_counter_updater.rb

Instance Method Summary collapse

Instance Method Details

#update_counters(name, from_time_ago) ⇒ Object

override counter threshold. update method counters from the given Time E.g. Post.update_counters(:num_reads, 1.hour.ago) will update all items that received hits in the last hour



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/visit_counter_updater/visit_counter_updater.rb', line 33

def update_counters(name, from_time_ago)
  set_name = VisitCounter::Key.generate(name, self)
  counters_in_timeframe = VisitCounter::Store.engine.get_all_by_range(set_name, from_time_ago.to_i, Time.now.to_i)
  obj_ids  = counters_in_timeframe.flat_map { |c| [c.split("::")[2].to_i] }
  objects = self.where(id: obj_ids)

  ## if no objects corresponding to the counters were found, remove them.
  counters = Helper.reject_objectless_counters(counters_in_timeframe, objects, obj_ids)

  hits, staged_count = Helper.get_count_stats(counters, objects, name)
  self.transaction do
    objects.zip(Helper.merge_array_values(hits, staged_count)).each do |o|
      VisitCounter::Store.engine.with_lock(o[0]) do
        o[0].class.update_all("#{name} = #{o[1]}", "id = #{o[0].id}")
      end
    end
  end
  VisitCounter::Store.engine.mnullify(counters)
end