public
Clone URL: git://github.com/robbyrussell/rubyurl.git
Search Repo:
Robby Russell (author)
Sun Mar 02 17:08:48 -0800 2008
commit  e0346a323c6c102e38481411c412fde1998de331
tree    c3b21f236df0397612e6bc6be0792034e1ea29c3
parent  61057f107e17827d1653fc9d858eb0f68d5fd405
rubyurl / app / models / link.rb
100644 49 lines (39 sloc) 1.29 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Link < ActiveRecord::Base
  TOKEN_LENGTH = 4
  
  has_many :visits
  has_many :spam_visits, :class_name => 'Visit', :conditions => ["flagged = 'spam'"]
  
  validates_presence_of :website_url, :ip_address
  validates_uniqueness_of :website_url, :token
  validates_format_of :website_url, :with => /^(http|https):\/\/[a-z0-9]/ix, :on => :save, :message => 'needs to have http(s):// in front of it', :if => Proc.new { |p| p.website_url? }
  
  before_create :generate_token
  
  def flagged_as_spam?
    self.spam_visits.empty? ? false : true
  end
  
  def add_visit(request)
    visit = visits.build(:ip_address => request.remote_ip)
    visit.save
    return visit
  end
  
  private
  
    def generate_token
      if (temp_token = random_token) and self.class.find_by_token(temp_token).nil?
        self.token = temp_token
        build_permalink
      else
        generate_token
      end
    end
    
    def build_permalink
      self.permalink = DOMAIN_NAME + self.token
    end
  
    def random_token
      characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
      temp_token = ''
      srand
      TOKEN_LENGTH.times do
        pos = rand(characters.length)
        temp_token += characters[pos..pos]
      end
      temp_token
    end
    
end