lib/eotb.rb in eotb-0.5.11 vs lib/eotb.rb in eotb-0.5.12

- old
+ new

@@ -1,49 +1,85 @@ require 'rubygems' require 'net/http' require 'timeout' require 'uri' require 'json' +require 'timer' class Eotb @@api_key = nil METHODS = [:to_actor, :to_subject, :to_json, :to_hash, :inspect] - def self.configure(api_key, events = 1, host = '127.0.0.1', port = '3000') + def self.configure(api_key) + @@host = "beta.beholder.ragnarson.com" + @@port = '80' @@api_key = api_key - @@uri = URI.parse('http://' + host + ':' + port + '/events/' + api_key) + @@uri = URI.parse('http://' + @@host + ':' + @@port + '/events/' + api_key) @@post = Net::HTTP::Post.new(@@uri.path) @@events = {} @@counter = 1 - events >= 1 ? @@reset = events : @@reset = 1 + @@reset = 100 + + Thread.new do + Timer.every(600.0) { |elapsed| + unless @@events.empty? + @@counter = @@reset + send + end + } + end unless ENV['RAILS_ENV'] == 'test' end def self.api_key @@api_key end - def self.register_event(actor, action, subject = {}) + def self.register_event(*args) + case args.size + when 1 + self._json_register_event(*args) + when 2,3 + self._base_register_event(*args) + else + raise ArgumentError, "wrong number of arguments (#{args.size} for 1,2 or 3)" + end + end + + def self._json_register_event(json) + json = JSON.parse json + args = [json["actor"],json["action"]] + args << json["subject"] if json["subject"] + self._base_register_event(*args) + end + + def self._base_register_event(actor, action, subject = {}) + unless ENV['RAILS_ENV'] == 'test' action = { "event#{@@counter}[action]" => action.to_s } - event = (hash_format(actor, :actor)).merge(action).merge(hash_format(subject, :subject)) + event = (hash_format(actor, :actor)).merge(action).merge(hash_format(subject, :subject)) - @@events.merge! event - if (@@counter == @@reset) - @@post.set_form_data(@@events) - @@counter = 1 - begin - Timeout::timeout(2) { - Net::HTTP.new(@@uri.host, @@uri.port).start.request(@@post) - } - rescue => e - logger = Logger.new("log/#{ENV['RAILS_ENV']}.log") - logger.error "ERROR eotb gem: " + e.to_s - rescue Timeout::Error => e - logger = Logger.new("log/#{ENV['RAILS_ENV']}.log") - logger.error "ERROR eotb gem: " + e.to_s + @@events.merge! event + if (@@counter == @@reset) + send + else + @@counter += 1 end - else - @@counter += 1 + end + end + + def self.send + @@post.set_form_data(@@events) + @@counter = 1 + begin + Timeout::timeout(2) { + Net::HTTP.new(@@uri.host, @@uri.port).start.request(@@post) + } + rescue => e + logger = Logger.new("log/#{ENV['RAILS_ENV']}.log") + logger.error "ERROR eotb gem: " + e.to_s + rescue Timeout::Error => e + logger = Logger.new("log/#{ENV['RAILS_ENV']}.log") + logger.error "ERROR eotb gem: " + e.to_s end end def self.value_format(value) value.send METHODS.find { |m| m if value.respond_to? m }