Permalink
Browse files

Populating petition reports with information from Google Analytics.

  • Loading branch information...
1 parent a21b01a commit 3ef434c0e4047a39f3d876bf2d73925626357b16 @rafaelpetry rafaelpetry committed Jan 3, 2013
Showing with 17 additions and 0 deletions.
  1. +4 −0 spec/worker/petition_report_populator_spec.rb
  2. +13 −0 worker/petition_reports_populator.rb
@@ -4,9 +4,11 @@
let(:petition) { create(:petition) }
before do
+ AnalyticsGateway.stub(:fetch_report_results => {"/petitions/#{petition.id}" => OpenStruct.new(:unique_pageviews => '3')})
3.times { create(:scheduled_email, petition: petition) }
2.times { create(:scheduled_email, petition: petition, opened_at: 1.hour.ago) }
create(:unsubscribe, sent_email: ScheduledEmail.last)
+
PetitionReportsPopulator.populate
end
@@ -17,4 +19,6 @@
its(:opened_emails_rate_day) { should eq 0.4 }
its(:unsubscribes_count_day) { should eq 1 }
its(:unsubscribes_rate_day) { should eq 0.2 }
+ its(:hit_count_day) { should eq 3 }
+ its(:hit_rate_day) { should eq 0.6 }
end
@@ -24,7 +24,10 @@ def populate
db = ActiveRecord::Base.connection
db.execute create_reports_query
+ analytics_data_per_period = {}
PERIODS.each do |period, starting_time|
+ analytics_data_per_period[period] = AnalyticsGateway.fetch_report_results(starting_time)
+
METRICS.each do |metric, metric_sql|
column_name = "#{metric}_#{period}"
select_query = metric_sql.call(starting_time)
@@ -33,6 +36,16 @@ def populate
end
end
+ PetitionReport.all.each do |report|
+ petition_path = Rails.application.routes.url_helpers.petition_path(report.petition_id)
+ PERIODS.each do |period, _|
+ method = :"hit_count_#{period}="
+ pageviews = analytics_data_per_period[period][petition_path].try(:unique_pageviews).try(:to_i)
+ report.send(method, pageviews)
+ end
+ report.save if report.changed?
+ end
+
rate_columns = PetitionReport.column_names.select {|name| name =~ /rate/ }
rate_columns.each do |column|
db.execute update_rate_query(column)

0 comments on commit 3ef434c

Please sign in to comment.