Take the 2008 Git User's Survey and help out! [ hide ]

public
Description: Your favorite URL-shortening service in all of Ruby land
Homepage: http://rubyurl.com
Clone URL: git://github.com/robbyrussell/rubyurl.git
Search Repo:
robbyrussell (author)
Thu Jan 17 10:46:05 -0800 2008
commit  c3f6c11cc0186ec217279f62acf6345849ff2049
tree    b91ca8eee1fa6b959e18ba8257f41dbc558d5b2b
parent  678d6db681303b09bd7f65ddda6e96ecb2088ecd
rubyurl / app / models / link.rb
100644 50 lines (40 sloc) 1.294 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
50
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 = Visit.new
    visit.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