Skip to content

Instantly share code, notes, and snippets.

@oelmekki
Created April 28, 2015 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oelmekki/2bb14079dfd08ff50fca to your computer and use it in GitHub Desktop.
Save oelmekki/2bb14079dfd08ff50fca to your computer and use it in GitHub Desktop.
# Allows to create event on piwik from server side code.
#
# Usage:
#
# piwik = Piwik.new
# piwik.create_event( category: 'sale', action: 'new_interface', name: '100_sales_from_same_country', value: 10_000 )
# piwik.create_event( name: 'user_changed_locale' )
#
#
# Required gems:
#
# * httparty
# * active_support (for `Hash#deep_merge`)
# * securerandom
#
#
# Required env vars:
#
# * PIWIK_HOST : host name for piwik server
# * PIWIK_SITE_ID : site id in piwik site manager
# * PIWIK_TOKEN : api token found in piwik user settings
#
# Token is used to force override location data to nowhere,
# so that geo stats aren't corrupted (each event would create
# a visit from your server location, otherwise).
#
class Piwik
include HTTParty
attr_reader :global_options
base_uri ENV[ 'PIWIK_HOST' ]
def initialize( options = {} )
options = convert_event_keys_for options
@global_options = { query: default_options }.deep_merge( query: options )
end
# Create an event on piwik.
#
# Any option will be passed to post data.
#
# Typically, you want to set one or several of those:
#
# * `:category` : event category
# * `:action` : event action
# * `:name` : event name (probably the most important)
# * `:value` : event value (money value for goal tracking)
#
# @param [Hash] options
# @return [HTTParty::Response]
def create_event( options )
options = convert_event_keys_for options
options = global_options.deep_merge( query: { url: url, rand: rand, action_name: 'Event' } ).deep_merge( query: options )
self.class.post( '/piwik.php', options )
end
private
def default_options
{
idsite: site_id,
rec: 1,
token_auth: token,
region: '0',
country: '0',
city: '0',
lat: '0',
long: '0',
new_visit: 1,
}
end
def site_id
ENV[ 'PIWIK_SITE_ID' ]
end
def token
ENV[ 'PIWIK_TOKEN' ]
end
def url
'/event-tracking'
end
def rand
SecureRandom.urlsafe_base64(8)
end
def convert_event_keys_for( options )
{ category: 'e_c', action: 'e_a', name: 'e_n', value: 'e_v' }.each do |local_name, api_name|
if options.has_key? local_name
value = options.delete local_name
options[ api_name ] = value
end
end
options
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment