Skip to content

Instantly share code, notes, and snippets.

@ricburton
Created August 6, 2012 10:07
Show Gist options
  • Save ricburton/3273139 to your computer and use it in GitHub Desktop.
Save ricburton/3273139 to your computer and use it in GitHub Desktop.
dashboard query in need of cosmetic surgery
class AnalyticsController < ApplicationController
def download
consumer = OAuth::Consumer.new('******.apps.googleusercontent.com', '******',
{:site => 'https://www.google.com',
:request_token_path => '/accounts/OAuthGetRequestToken',
:access_token_path => '/accounts/OAuthGetAccessToken',
:authorize_path => '/accounts/OAuthAuthorizeToken'}
)
token = '*****'
secret = '******'
access_token = OAuth::AccessToken.new(consumer, token, secret)
Garb::Session.access_token = access_token
profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == 'UA-8697810-2'}
puts profile
today = Date.today
history = 30 # add 1 to this for the number of days that will be received
while history >= 0
start_date = today - history
end_date = today - history
data = Hash.new
data["branded"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :medium.matches => "organic", :keyword.contains => "wood"} ).first
data["nonbranded"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :medium.matches => "organic", :keyword.does_not_contain => "wood|(not provided)|np|(not set)"} ).first
data["unknown"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :medium.matches => "organic", :keyword.contains => "(not provided)|np|(not set)"} ).first
data["affiliate"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :source.contains => "track.webgains.com"} ).first
data["social"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :source.contains => "facebook\.com|twitter\.com|pinterest\.com|youtube|flickr" } ).first
data["referral"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :medium.matches => "referral", :source.does_not_contain => "facebook\.com|twitter\.com|pinterest\.com|youtube|flickr|track.webgains.com" } ).first
data["paid"] = profile.stats(start_date: start_date, end_date: end_date, segment_id: '-4').first
data["direct"] = profile.stats(start_date: start_date, end_date: end_date, segment_id: '-7').first
data["email"] = profile.stats(start_date: start_date, end_date: end_date, filters: { :medium.contains => "email|Email"} ).first
data.each do |source,results|
data_check = Analytic.find_or_create_by_start_date_and_source(start_date, source)
data_check.update_attributes!({
start_date: start_date,
end_date: end_date,
source: source,
site: "woodhouse",
visits: results.visits,
revenue: results.transaction_revenue,
revenue_per_transaction: results.revenue_per_transaction,
transactions: results.transactions,
items_per_purchase: results.items_per_purchase,
goal_starts: results.goal2_starts,
goal_completes: results.goal2_completions,
goal_conversion: results.goal2_conversion_rate,
goal_abandon: results.goal2_abandon_rate})
puts source.to_s + " " + results.to_s
end
history -= 1
puts "DONE A DAY!"
end
respond_to do |format|
format.html
end
end
end
@bostwick
Copy link

class Analytic

    # Public: Download profile statistics from Google Analytics and update 
    # the database with the new data.
    # Returns nil.
    def self.download
        profile = google_analytics_profile
        today = Date.today
        days_ago = 30 # How many days back to read.

        (0..days_ago).do |n_days_ago|
            start_date = end_date = today - n_days_ago
            profile_stats = get_profile_stats(profile, start_date, end_date)

            profile_stats.each do |source, results|
                update_from_profile_stats(source, results)
            end

            puts "Finished #{start_date.to_s}"
        end
    end

    private

    # Private: Get an OAuth'ed consumer for google analytics
    # Returns an OAuth::Consumer
    def self.google_analytics_profile
        consumer = OAuth::Consumer.new('******.apps.googleusercontent.com', '******',
                    { :site => 'https://www.google.com',
                      :request_token_path => '/accounts/OAuthGetRequestToken',
                      :access_token_path => '/accounts/OAuthGetAccessToken',
                      :authorize_path => '/accounts/OAuthAuthorizeToken'
                    })

        token = '*****'
        secret = '******'

        access_token = OAuth::AccessToken.new(consumer, token, secret)
        Garb::Session.access_token = access_token
        profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == 'UA-8697810-2'}

        puts profile
        return profile
    end

    # Private: Download the necessary profile stats from google analytics
    # Returns a hash that maps from stat to its value
    def self.get_profile_stats(profile, start_date, end_date)
        data = Hash.new
        source_filters = {
            'branded' => { :medium.matches => "organic", :keyword.contains => "wood"},
            'nonbranded' => { :medium.matches => "organic", :keyword.does_not_contain => "wood|(not provided)|np|(not set)" },
            'unknown' => { :medium.matches => "organic", :keyword.contains => "(not provided)|np|(not set)"},
            'affiliate' => { :source.contains => "track.webgains.com"},
            'social' => { :source.contains => "facebook\.com|twitter\.com|pinterest\.com|youtube|flickr" },
            'referral' => { :medium.matches => "referral", :source.does_not_contain => "facebook\.com|twitter\.com|pinterest\.com|youtube|flickr|track.webgains.com" },
            'paid' => {},
            'direct' => {},
            'email' => { :medium.contains => "email|Email"}
        }

        source_filters.each do |source, filter|
            stat = profile.stats(start_date: start_date, end_date: end_date,
                                 filter: filter).first
            data[source] = stat
        end

        # paid and direct sources are special
        data["paid"] = profile.stats(start_date: start_date, end_date: end_date, 
                            segment_id: '-4').first
        data["direct"] = profile.stats(start_date: start_date, end_date: end_date, 
                            segment_id: '-7').first

        return data
    end

    # Private: Create or Update an analytic from stats downloaded from a 
    # google analytics profile.
    # Returns nil
    def self.update_from_profile_stats(source, results)
        data_check = Analytic.find_or_create_by_start_date_and_source(start_date, source)
        data_check.update_attributes!({
            start_date:               start_date, 
            end_date:                 end_date,
            source:                   source,
            site:                     "woodhouse",
            visits:                   results.visits,
            revenue:                  results.transaction_revenue,
            revenue_per_transaction:  results.revenue_per_transaction,
            transactions:             results.transactions,
            items_per_purchase:       results.items_per_purchase,
            goal_starts:              results.goal2_starts,
            goal_completes:           results.goal2_completions,
            goal_conversion:          results.goal2_conversion_rate,
            goal_abandon:             results.goal2_abandon_rate})

        puts source.to_s + " " + results.to_s
    end

end # class Analytic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment