lib/eotb.rb in eotb-0.4.1 vs lib/eotb.rb in eotb-0.4.2

- old
+ new

@@ -10,27 +10,53 @@ @@post = Net::HTTP::Post.new(@@uri.path) @@api_key = { "event[app_id]" => api_key } end def self.register_event(actor, action, subject = {}) - actor = { "event[actor]" => format(actor) } - action = { "event[action]" => action.to_s } - data = {} - subject.each { |key, value| data["event[subject][#{key.to_s}]"] = format(value) } - - event = @@api_key.merge(actor).merge(action).merge(data) - + action = { "event[action]" => action.to_s } + event = @@api_key.merge(hash_format(actor, :actor)).merge(action).merge(hash_format(subject, :subject)) @@post.set_form_data(event) Net::HTTP.new(@@uri.host, @@uri.port).start.request(@@post) end - def self.format(object) - if object.respond_to? :to_json + def self.value_format(object) + if object.respond_to? :to_actor + object.to_actor + elsif object.respond_to? :to_subject + object.to_subject + elsif object.respond_to? :to_json object.to_json elsif object.respond_to? :to_hash - object.to_hash.to_json + object.to_hash else object.inspect end + 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) + a = hash_flatten(hash).map do |k, v| + key = k.map{ |e| "[#{e}]" }.join + "\"event[#{type}]#{key}\" => #{value_format(v)}" + end + a.join(', ') + else + a = "\"event[#{type}]\" => #{value_format(hash)}" + end + eval '{' + a + '}' end end \ No newline at end of file