Skip to content

Instantly share code, notes, and snippets.

@rafaelmadeira
Forked from mazuhl/application_controller.rb
Created November 29, 2012 11:26
Show Gist options
  • Save rafaelmadeira/4168362 to your computer and use it in GitHub Desktop.
Save rafaelmadeira/4168362 to your computer and use it in GitHub Desktop.
Putting together a traffic analytics model and controller for a Ruby on Rails app based on this presentation about Scribd http://www.scribd.com/doc/49575/Scaling-Rails-Presentation-From-Scribd-Launch (see slides 17 to 22).
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
before_filter :log_page_view, :except => [:destroy]
private
def log_page_view
PageView.log_page_view(request,session)
end
end
class CreatePageViews < ActiveRecord::Migration
def self.up
create_table :page_views do |t|
t.column "user_id", :integer
t.column "request_url", :string, :limit => 200
t.column "session", :string, :limit => 32
t.column "ip_address", :string, :limit => 16
t.column "referer", :string, :limit => 200
t.column "user_agent", :string, :limit => 200
t.column "created_at", :timestamp
end
end
def self.down
drop_table :page_views
end
end
class PageView < ActiveRecord::Base
validates_presence_of :ip_address
validates_presence_of :user_agent
# just so you know...
# you'd do this with SQL directly, rather than using AR models
# but for a couple hundred page views, this will be OK
def self.log_page_view(request,session)
pageview = PageView.new
pageview.user_id = session[:user_id] || "0"
pageview.request_url = request.url
pageview.session = session[:session_id] || "unknown"
pageview.ip_address = request.remote_ip
pageview.referer = request.referer
pageview.user_agent = request.headers["User-Agent"]
pageview.save
end
end
class PageViewsController < ApplicationController
layout 'layout'
def index
@pageviews = PageView.find(:all)
respond_to do |format|
format.html # index.html.erb
end
end
# DELETE /posts/1
# DELETE /posts/1.xml
def destroy
@pageview = PageView.find(params[:id])
@pageview.destroy
respond_to do |format|
format.html { redirect_to(page_views_url) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment