Permalink
Browse files

added has many visits to urls

  • Loading branch information...
1 parent e9fec6d commit cfa8a90b8692786386611b67f8d64bf5b26aec1f Mike Mondragon committed Apr 20, 2008
Showing with 44 additions and 5 deletions.
  1. +31 −3 hurl/models.rb
  2. +13 −2 test/test_models.rb
View
@@ -15,6 +15,8 @@ module Hurl::Models
class Url < Base
+ has_many :visits
+
##
# The maximum power of the base 62 keys
# 62 ** 5 == 916M or almost 1B
@@ -38,12 +40,24 @@ def token
end
##
- # Look up the URL for the base62 token and increment the counter.
+ #
+
+ def add_visit(env)
+ options = {}
+ options[:remote_addr] = env.REMOTE_ADDR if env.REMOTE_ADDR
+ options[:referer] = env.HTTP_REFERER if env.HTTP_REFERER
+ options[:user_agent] = env.HTTP_USER_AGENT if env.HTTP_USER_AGENT
+ visits.create!(options)
+ end
- def self.find_by_token(token)
+ ##
+ # Look up the URL for the base62 token, increment the counter and a visit.
+
+ def self.find_by_token(token, env)
key = token.alphadecimal
url = self.find(:first, :conditions => {:key => key})
raise ActiveRecord::RecordNotFound.new("url for '#{key}' not found") unless url
+ url.add_visit(env)
url.increment!(:hits)
url
end
@@ -86,6 +100,10 @@ def valid_url?
end
+ class Visit < Base
+ belongs_to :url
+ end
+
##
# Camping migration to create our database
@@ -105,7 +123,17 @@ def self.up
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
- add_index :hurl_urls, :key, :unique => true
+ create_table :hurl_visits, :force => true do |t|
+ t.column :url_id, :integer, :null => false
+ t.column :remote_addr, :string
+ t.column :referer, :text
+ t.column :user_agent, :string
+ t.column :created_at, :datetime
+ t.column :updated_at, :datetime
+ end
+ add_index :hurl_urls, :key, :unique => true
+ add_index :hurl_urls, :remote_addr
+ add_index :hurl_visits, :url_id
# for XXX hax above
# Url.create(:key => 'it'.alphadecimal, :url => 'http://hurl.it')
View
@@ -16,6 +16,8 @@ class TestUrl < Camping::UnitTest
def setup
Hurl::Models::Url.delete_all
+ @env = stub(:REMOTE_ADDR => '127.0.0.10', :HTTP_REFERER => 'http://example.com/',
+ :HTTP_USER_AGENT => 'foo agent')
end
def test_validity
@@ -38,8 +40,10 @@ def test_find_by_token_increments_hits
u = Hurl::Models::Url.create :url => 'http://example.com/'
u = Hurl::Models::Url.find(:first, :conditions => {:key => u.key})
count = u.hits
- u = Hurl::Models::Url.find_by_token(u.token)
- assert_equal (count + 1), u.hits
+ assert_difference(Hurl::Models::Visit, :count, 1) do
+ u = Hurl::Models::Url.find_by_token(u.token, @env)
+ assert_equal (count + 1), u.hits
+ end
end
def test_2783_it_key_cannot_be_destroyed
@@ -48,4 +52,11 @@ def test_2783_it_key_cannot_be_destroyed
Hurl::Models::Url.destroy(u)
end
end
+
+ def test_add_visit
+ u = Hurl::Models::Url.create :url => 'http://example.com/'
+ assert_difference(Hurl::Models::Visit, :count, 1) do
+ u.add_visit(@env)
+ end
+ end
end

0 comments on commit cfa8a90

Please sign in to comment.