2013-02-05 14:16:51 -05:00
|
|
|
require 'ipaddr'
|
|
|
|
|
|
|
|
class View < ActiveRecord::Base
|
2013-02-07 10:45:24 -05:00
|
|
|
belongs_to :parent, polymorphic: true
|
2013-02-05 14:16:51 -05:00
|
|
|
belongs_to :user
|
2013-06-25 00:18:54 -04:00
|
|
|
validates_presence_of :parent_type, :parent_id, :ip_address, :viewed_at
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2013-10-04 03:00:23 -04:00
|
|
|
def self.create_for_parent(parent_class, parent_id, ip, user_id)
|
2013-02-05 14:16:51 -05:00
|
|
|
# Only store a view once per day per thing per user per ip
|
2013-10-04 03:00:23 -04:00
|
|
|
redis_key = "view:#{parent_class.name}:#{parent_id}:#{Date.today.to_s}"
|
|
|
|
if user_id
|
|
|
|
redis_key << ":user-#{user_id}"
|
2013-02-05 14:16:51 -05:00
|
|
|
else
|
|
|
|
redis_key << ":ip-#{ip}"
|
|
|
|
end
|
|
|
|
|
|
|
|
if $redis.setnx(redis_key, "1")
|
|
|
|
$redis.expire(redis_key, 1.day.to_i)
|
|
|
|
|
|
|
|
View.transaction do
|
2013-10-04 03:00:23 -04:00
|
|
|
View.create!(parent_id: parent_id, parent_type: parent_class.to_s, ip_address: ip, viewed_at: Date.today, user_id: user_id)
|
2013-02-05 14:16:51 -05:00
|
|
|
|
|
|
|
# Update the views count in the parent, if it exists.
|
2013-10-04 03:00:23 -04:00
|
|
|
if parent_class.columns_hash["views"]
|
|
|
|
parent_class.where(id: parent_id).update_all 'views = views + 1'
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2013-10-04 03:00:23 -04:00
|
|
|
|
|
|
|
def self.create_for(parent, ip, user=nil)
|
|
|
|
user_id = user.id if user
|
|
|
|
create_for_parent(parent.class, parent.id, ip, user_id)
|
|
|
|
end
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
2013-05-23 22:48:32 -04:00
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: views
|
|
|
|
#
|
|
|
|
# parent_id :integer not null
|
|
|
|
# parent_type :string(50) not null
|
|
|
|
# viewed_at :date not null
|
|
|
|
# user_id :integer
|
2013-06-25 00:18:54 -04:00
|
|
|
# ip_address :string not null
|
2013-05-23 22:48:32 -04:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
2013-10-03 23:28:49 -04:00
|
|
|
# index_views_on_parent_id_and_parent_type (parent_id,parent_type)
|
|
|
|
# index_views_on_user_id_and_parent_type_and_parent_id (user_id,parent_type,parent_id)
|
2013-05-23 22:48:32 -04:00
|
|
|
#
|
|
|
|
|