From 5066682e7abdb11719d3f82102f6550fe82b1340 Mon Sep 17 00:00:00 2001 From: Gosha Arinich Date: Sat, 2 Mar 2013 12:33:29 +0300 Subject: [PATCH] move IncomingLink callbacks into their own methods --- app/models/incoming_link.rb | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/app/models/incoming_link.rb b/app/models/incoming_link.rb index f5675d984..8d7c9cbb3 100644 --- a/app/models/incoming_link.rb +++ b/app/models/incoming_link.rb @@ -3,33 +3,36 @@ class IncomingLink < ActiveRecord::Base validates :domain, length: { in: 1..100 } validates :referer, length: { in: 3..1000 } - validates_presence_of :url + validates :url, presence: true - # Extract the domain - before_validation do - # Referer (remote URL) + before_validation :extract_domain + before_validation :extract_topic_and_post + after_create :update_link_counts + + # Internal: Extract the domain from link. + def extract_domain if referer.present? - parsed = URI.parse(referer) - self.domain = parsed.host + self.domain = URI.parse(referer).host 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? - parsed = URI.parse(url) begin params = Rails.application.routes.recognize_path(parsed.path) - self.topic_id = params[:topic_id] if params[:topic_id].present? - self.post_number = params[:post_number] if params[:post_number].present? + self.topic_id = params[:topic_id] + self.post_number = params[:post_number] rescue ActionController::RoutingError # If we can't route to the url, that's OK. Don't save those two fields. end end end - # Update appropriate incoming link counts - after_create do + # Internal: Update appropriate link counts. + def update_link_counts if topic_id.present? exec_sql("UPDATE topics SET incoming_link_count = incoming_link_count + 1