Skip to content

Instantly share code, notes, and snippets.

@nicoolas25

nicoolas25/example.rb

Last active Aug 29, 2015
Embed
What would you like to do?
Monkey patch to save queries with keen.io
Keen.save_query('message_by_weekday', {
analysis_type: 'count',
event_collection: 'message_received',
group_by: 'time.wday',
})
require 'keen'
#
# Patch keen gem to allow saved queries
#
module Keen
module HTTP
class Sync
def put(options)
path, headers, body = options.values_at(
:path, :headers, :body)
@http.put(path, body, headers)
end
end
end
end
module Keen
class Client
module SavingMethods
def save_query(query_name, properties)
ensure_project_id!
ensure_write_key!
save_body(
api_saved_query_resource_path(query_name),
MultiJson.encode(properties),
'save')
end
private
def save_body(path, body, error_method)
begin
response = Keen::HTTP::Sync.new(
self.api_url, self.proxy_url).put(
:path => path,
:headers => api_headers(self.master_key, 'sync'),
:body => body)
rescue Exception => http_error
raise HttpError.new("HTTP #{error_method} failure: #{http_error.message}", http_error)
end
process_response(response.code, response.body.chomp)
end
def api_saved_query_resource_path(query_name)
"/#{self.api_version}/projects/#{self.project_id}/saved_queries/#{query_name}"
end
end
end
Client.__send__(:include, Keen::Client::SavingMethods)
end
module Keen
class << self
def_delegators :default_client,
:save_query
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment