Sha256: 607bdeaa7da69f402b1d699ab25d4d05f4aefd50cbf2f23a5012a1630761f9a8

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

require 'rubygems'
require 'net/http'
require 'timeout'
require 'uri'
require 'json'

class Eotb

  METHODS = [:to_actor, :to_subject, :to_json, :to_hash, :inspect]
    
  def self.configure(api_key, events = 1, host = '127.0.0.1', port = '3000')
    @@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
  end

  
  def self.register_event(actor, action, subject = {})
    action = { "event#{@@counter}[action]" => action.to_s }    
    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
      end
    else
      @@counter += 1
    end
  end
  
  def self.value_format(value)
    value.send METHODS.find { |m| m if value.respond_to? m }
  end
  
  def self.hash_flatten(hash)
    hash.inject({}) do |h, (k, v)|
      if v.is_a?(Hash)
        hash_flatten(v).each do |sk, sv|
          h[[k] + sk] = sv
        end
      else
        k = k ? [k] : []
        h[k] = v
      end
      h
    end
  end

  def self.hash_format(hash, type)
    if hash.is_a?(Hash)
      h = hash_flatten(hash).map do |k, v|
        key = k.map{ |e| "[#{e}]" }.join
        "\"event#{@@counter}[#{type}]#{key}\" => #{value_format(v)}"
      end.join(', ')
    else
      h = "\"event#{@@counter}[#{type}]\" => #{value_format(hash)}"
    end
    eval "{#{h.to_s}}"
  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eotb-0.5.7 lib/eotb.rb