2013-02-05 14:16:51 -05:00
|
|
|
class IncomingLink < ActiveRecord::Base
|
|
|
|
belongs_to :topic
|
|
|
|
|
2013-02-28 13:54:12 -05:00
|
|
|
validates :domain, length: { in: 1..100 }
|
|
|
|
validates :referer, length: { in: 3..1000 }
|
2013-03-02 04:33:29 -05:00
|
|
|
validates :url, presence: true
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2013-03-02 04:33:29 -05:00
|
|
|
before_validation :extract_domain
|
|
|
|
before_validation :extract_topic_and_post
|
|
|
|
after_create :update_link_counts
|
|
|
|
|
|
|
|
# Internal: Extract the domain from link.
|
|
|
|
def extract_domain
|
2013-02-05 14:16:51 -05:00
|
|
|
if referer.present?
|
2013-03-02 04:33:29 -05:00
|
|
|
self.domain = URI.parse(referer).host
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
2013-03-02 04:33:29 -05:00
|
|
|
end
|
2013-02-05 14:16:51 -05:00
|
|
|
|
2013-03-02 04:33:29 -05:00
|
|
|
# Internal: If link is internal and points to topic/post, extract their IDs.
|
|
|
|
def extract_topic_and_post
|
2013-02-05 14:16:51 -05:00
|
|
|
if url.present?
|
|
|
|
parsed = URI.parse(url)
|
|
|
|
|
|
|
|
begin
|
|
|
|
params = Rails.application.routes.recognize_path(parsed.path)
|
2013-03-02 04:33:29 -05:00
|
|
|
self.topic_id = params[:topic_id]
|
|
|
|
self.post_number = params[:post_number]
|
2013-02-05 14:16:51 -05:00
|
|
|
rescue ActionController::RoutingError
|
|
|
|
# If we can't route to the url, that's OK. Don't save those two fields.
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-03-02 04:33:29 -05:00
|
|
|
# Internal: Update appropriate link counts.
|
|
|
|
def update_link_counts
|
2013-02-05 14:16:51 -05:00
|
|
|
if topic_id.present?
|
|
|
|
exec_sql("UPDATE topics
|
2013-02-07 10:45:24 -05:00
|
|
|
SET incoming_link_count = incoming_link_count + 1
|
|
|
|
WHERE id = ?", topic_id)
|
2013-02-05 14:16:51 -05:00
|
|
|
if post_number.present?
|
2013-02-07 10:45:24 -05:00
|
|
|
exec_sql("UPDATE posts
|
|
|
|
SET incoming_link_count = incoming_link_count + 1
|
|
|
|
WHERE topic_id = ? and post_number = ?", topic_id, post_number)
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
2013-02-07 10:45:24 -05:00
|
|
|
end
|
2013-02-05 14:16:51 -05:00
|
|
|
end
|
|
|
|
end
|