public
Description: simple mongrel handler for a sweet hit counter
Homepage: http://errcount.com
Clone URL: git://github.com/pjhyett/errcount.git
Click here to lend your support to: errcount and make a donation at www.pledgie.com !
pjhyett (author)
Fri Feb 15 13:07:39 -0800 2008
commit  9dd900574c6306ff13c92dbb4abcc7db4fdf51a1
tree    6134025854daab1d71317ebd21c26708bdf719c6
errcount / counter.rb
100644 30 lines (24 sloc) 1.186 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
class Counter < Mongrel::HttpHandler
  Style = ".ctr { background-image:url(http://errcount.com/images/counter.png); float:left; width:15px; height:20px; }"
  
  def process(request, response)
    response.start(200) do |head, out|
      # grab row from db
      id = request.params["PATH_INFO"][/\d+/].to_i
      row = ActiveRecord::Base.connection.select_one("select url, hits from sites where id = #{id}")
      
      # check for correct referrer
      if Regexp.new(row["url"]) =~ request.params["HTTP_REFERER"]
        ActiveRecord::Base.connection.update("update sites set hits = hits + 1 where id = #{id}")
      end
      
      # build counter javascript
      counter = %{var counter='<style>#{Style}</style><div style="cursor:pointer" onclick="window.location=\\'http://errcount.com\\'">}
      row["hits"].to_s.split(//).each do |num|
        counter += %{<div class="ctr" style="background-position:#{150 - (15 * num.to_i)}px 0;"></div>}
      end
      counter += "</div>';document.write(counter);"
      
      # serve it up
      head["Content-Type"] = "text/javascript"
      out.write counter
    end
  end
end
 
uri "/ctr", :handler => Counter.new, :in_front => true