move IncomingLink callbacks into their own methods

This commit is contained in:
Gosha Arinich 2013-03-02 12:33:29 +03:00
parent 9858beb6af
commit 5066682e7a
1 changed files with 15 additions and 12 deletions

View File

@ -3,33 +3,36 @@ class IncomingLink < ActiveRecord::Base
validates :domain, length: { in: 1..100 } validates :domain, length: { in: 1..100 }
validates :referer, length: { in: 3..1000 } validates :referer, length: { in: 3..1000 }
validates_presence_of :url validates :url, presence: true
# Extract the domain before_validation :extract_domain
before_validation do before_validation :extract_topic_and_post
# Referer (remote URL) after_create :update_link_counts
# Internal: Extract the domain from link.
def extract_domain
if referer.present? if referer.present?
parsed = URI.parse(referer) self.domain = URI.parse(referer).host
self.domain = parsed.host
end end
end
# Our URL # Internal: If link is internal and points to topic/post, extract their IDs.
def extract_topic_and_post
if url.present? if url.present?
parsed = URI.parse(url) parsed = URI.parse(url)
begin begin
params = Rails.application.routes.recognize_path(parsed.path) params = Rails.application.routes.recognize_path(parsed.path)
self.topic_id = params[:topic_id] if params[:topic_id].present? self.topic_id = params[:topic_id]
self.post_number = params[:post_number] if params[:post_number].present? self.post_number = params[:post_number]
rescue ActionController::RoutingError rescue ActionController::RoutingError
# If we can't route to the url, that's OK. Don't save those two fields. # If we can't route to the url, that's OK. Don't save those two fields.
end end
end end
end end
# Update appropriate incoming link counts # Internal: Update appropriate link counts.
after_create do def update_link_counts
if topic_id.present? if topic_id.present?
exec_sql("UPDATE topics exec_sql("UPDATE topics
SET incoming_link_count = incoming_link_count + 1 SET incoming_link_count = incoming_link_count + 1