Module: ARCounter

Extended by:
ActiveSupport::Concern
Defined in:
lib/ar_counter.rb,
lib/ar_counter/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#count_target(target) ⇒ Object



73
74
75
76
77
# File 'lib/ar_counter.rb', line 73

def count_target(target)
  sql = "SELECT #{target.to_s}_count from #{self.class.to_s.downcase}_stats where #{self.class.to_s.downcase}_id=#{self.id}"
  query = ActiveRecord::Base.connection.execute(sql)
  query.first ? query.first[0].to_i : 0
end

#counter_sql(counter_cached, increment_by) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/ar_counter.rb', line 42

def counter_sql(counter_cached, increment_by)
  counter_cached.each do |klas|
    stat_table      = "#{klas}_stats"
    owner_id_column = "#{klas}_id"
    klass_id = self.send("#{klas}_id")
    sql_for_increment(stat_table, stat_column, owner_id_column, klass_id, increment_by)
  end
end

#decrease_counter_statsObject



38
39
40
# File 'lib/ar_counter.rb', line 38

def decrease_counter_stats
  counter_sql @@counter_cached, -1
end

#increase_counter_statsObject



34
35
36
# File 'lib/ar_counter.rb', line 34

def increase_counter_stats
  counter_sql @@counter_cached, 1
end

#sql_for_add(stat_table, stat_column, owner_id_column, klass_id) ⇒ Object



57
58
59
60
61
# File 'lib/ar_counter.rb', line 57

def sql_for_add(stat_table, stat_column, owner_id_column, klass_id)
  sql = "INSERT INTO #{stat_table} (#{owner_id_column},#{stat_column}) VALUES (#{klass_id},1) \
         ON DUPLICATE KEY UPDATE #{stat_column}=#{stat_column}+1"
  ActiveRecord::Base.connection.execute(sql) if stat_table && owner_id_column && klass_id
end

#sql_for_increment(stat_table, stat_column, owner_id_column, klass_id, increment_by) ⇒ Object



63
64
65
66
67
# File 'lib/ar_counter.rb', line 63

def sql_for_increment(stat_table, stat_column, owner_id_column, klass_id, increment_by)
  sql = "INSERT INTO #{stat_table} (#{owner_id_column},#{stat_column}) VALUES (#{klass_id},1) \
         ON DUPLICATE KEY UPDATE #{stat_column}=#{stat_column}+#{increment_by}"
  ActiveRecord::Base.connection.execute(sql) if stat_table && owner_id_column && klass_id
end

#sql_for_subtract(stat_table, stat_column, owner_id_column, klass_id) ⇒ Object

SQL



52
53
54
55
# File 'lib/ar_counter.rb', line 52

def sql_for_subtract(stat_table, stat_column, owner_id_column, klass_id)
  sql = "UPDATE #{stat_table} SET #{stat_column}=#{stat_column}-1 WHERE #{owner_id_column}=#{klass_id}"
  ActiveRecord::Base.connection.execute(sql) if stat_table && owner_id_column && klass_id
end

#stat_columnObject



69
70
71
# File 'lib/ar_counter.rb', line 69

def stat_column
  "#{self.class.to_s.pluralize.downcase}_count"
end