Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting query results with Legato gem

Trying to get query results from Google Analytics using Legato gem (following a previous recommendation I go there + some research). Seems to be simple to define my query, however I fail to understand how to actually get the results. Reading the readme shows how to build some "building blocks", but I fail to get an object where I can read the results from.

Maybe I missed something, and the query results should be written directly to the model (DB), which is not what I want (I wanted to go over them first). Maybe that's the reason I'm not seeing anything.

So can someone please share an example how to read the results? For example, just print the pageviews to the screen.

Thanks

like image 736
user2339344 Avatar asked Jun 13 '13 08:06

user2339344


1 Answers

So here's the way I've found to use it: You create a class that defines the "model" of your query (and like Active-Model returning relations, you can also concatenate here). In this example:

  • The model/query check for pageviews & unique-pageviews within the ga:pagePathLevel1 dimension.
  • There is an optional filter you can use, looking for 'index' within the pagePathLevel1 (and as you can see, you can chose to use it or not, add more filters, concatenate them, etc.

Also note that the filter & result just return a "query" (just like ActiveModel::Relation), where the execution is done by invoking something on it, like 'each' or 'to_a', etc.

class Pageviews
  extend Legato::Model

  metrics :pageviews, :uniquePageviews
  dimensions :pagePathLevel1

  filter(:by_index_in_path_level_1) {|page_path_level1| contains(:pagePathLevel1, 'index')}

  def self.query(profile, start_date, end_date)
    Pageviews.results(profile,
                      :start_date => start_date,
                      :end_date => end_date
    )
    # Just for reference, sorting descending by pageviews is done by:   :sort => '-pageviews'
  end

  def self.query_index(profile, start_date, end_date)
    Pageviews.by_index_in_path_level_1.results(profile,
                                               :start_date => start_date,
                                               :end_date => end_date
    )
  end
end

Once this is ready, you can do something like:

Pageviews.query(profile, start_date, end_date).each do |result|
    # Just print the pageviews & unique-pageviews, for example
    puts result.try(:pageviews)
    puts result.try(:uniquePageviews)
end

Lastly, I recommand that you first explore with Google Analytics Query Explorer.

I hope you can find this example helpful

like image 183
user2339344 Avatar answered Oct 10 '22 17:10

user2339344