views:

28

answers:

1

I'm building a pageview counter for my app using the Garb Ruby wrapper for the Google Analytics API. Doing so means creating a new Module in the 'lib' folder, in which I create a class like this:

#lib/Analyze.rb

...
class Report
  extend Garb::Resource
  metrics :pageviews
  dimensions :page_path
  filters :page_path.eql => '/' #the path of the page I instantiate this class on
end

#followed by a method for instantiating this class

I need filters :page_path.eql => to be the path of the page in which I call the method. I've tried things like request.request_uri or url_for(:action => 'show' :controllers => 'users' :id => params[:id]) but don't know how to specify the page path in this class definition.

A: 

This will break MVC encapsulation - I think you should be creating a before filter in your application_controller that passes the request data you need to your class.

EDIT

If you want to build a one-off report for a particular page, I think you'll need to do something like this:

profile = Garb::Profile.first('UA-XXXX-XX')

report = Garb::Report.new(profile)
report.metrics :pageviews
report.dimensions :page_path
report.filters :page_path.eql => request.request_uri 

report.results

Again, if you're having this on every page, a before filter would be wise, I think. Pretty sure it's going to slow your app down a lot, though.

This is covered in the docs.

Mr. Matt
What does passing request data back to the class look like? I know I can't just pass a variable into the class definition. Sorry, still a fairly new programmer.
kateray
I think you want to build a one-off report for each page - I've updated my answer
Mr. Matt
Okay, this does work for me but also makes it slower. If you come up with any other ways of doing it, love to know. Thanks.
kateray
Yeah - it will slow it down as you're making a request to Analytics on each page load. You could cache the values returned, and decouple the request for the report by doing it in a background job. This won't give you up-to-the-second counters, but it will alleviate the slowness.
Mr. Matt